<?php

namespace App\Services;

/**
 * Resolves which global translation language row franchises may use for display, sync, diffs,
 * reset, and accept-update — aligned with translate_templates publication rules.
 */
class FranchiseGlobalSourceResolver
{
    public function __construct(
        private readonly TranslateTemplatePublishEligibilityService $translateTemplatePublishEligibility,
    ) {
    }

    /**
     * Global source language for a franchise UI / sync context: preferred language when its
     * website language template is officially published, otherwise English.
     */
    public function effectiveGlobalSourceLanguage(string $franchisePreferredLanguageCode): string
    {
        $code = strtolower(trim((string) $franchisePreferredLanguageCode));
        if ($code === '' || $code === 'english') {
            $code = 'en';
        }
        if ($code === 'en') {
            return 'en';
        }
        if ($this->translateTemplatePublishEligibility->isLanguageTemplatePublished($code)) {
            return $code;
        }

        return 'en';
    }
}
