<?php

namespace MintyPHP\Service\User;

use MintyPHP\Http\Request;
use MintyPHP\I18n;
use MintyPHP\Repository\Tenant\UserTenantRepository;
use MintyPHP\Service\Auth\TenantSsoService;

class UserAccessTemplateService
{
    public function __construct(
        private readonly TenantSsoService $tenantSsoService,
        private readonly UserDirectoryGateway $userDirectoryGateway,
        private readonly UserTenantRepository $userTenantRepository
    ) {
    }

    // Builds locale-aware template variables shared by mail and PDF onboarding output.
    public function buildContext(array $user): array
    {
        $locale = $this->resolveLocale($user);
        $name = trim((string) (($user['first_name'] ?? '') . ' ' . ($user['last_name'] ?? '')));
        $isGerman = str_starts_with($locale, 'de');
        $greeting = $isGerman ? 'Hallo' : 'Hello';
        if ($name !== '') {
            $greeting .= ' ' . $name;
        }
        $greeting .= ',';

        $loginUrl = $this->resolveTenantLoginUrl($user, $locale);
        $resetUrl = appUrl(Request::withLocale('password/forgot', $locale));

        // Temporarily switch locale so subject translation matches recipient language.
        $previousLocale = I18n::$locale ?? null;
        I18n::$locale = $locale;
        $subject = t('Your access details');
        I18n::$locale = $previousLocale;

        return [
            'locale' => $locale,
            'subject' => $subject,
            'vars' => [
                'app_name' => appTitle(),
                'app_logo_url' => appLogoUrlAbsolute(128),
                'imprint_url' => appUrl(Request::withLocale('imprint', $locale)),
                'privacy_url' => appUrl(Request::withLocale('privacy', $locale)),
                'greeting' => $greeting,
                'username' => (string) ($user['email'] ?? ''),
                'login_url' => $loginUrl,
                'reset_url' => $resetUrl,
            ],
        ];
    }

    public function resolveLocale(array $user): string
    {
        // Keep user locale within configured APP_LOCALES; otherwise fallback to app default.
        $locale = strtolower(trim((string) ($user['locale'] ?? '')));
        if ($locale === '') {
            $locale = I18n::$locale ?? I18n::$defaultLocale;
        }
        $available = defined('APP_LOCALES') && is_array(APP_LOCALES) ? APP_LOCALES : [];
        if ($available && !in_array($locale, $available, true)) {
            $locale = I18n::$defaultLocale;
        }
        return $locale;
    }

    private function resolveTenantLoginUrl(array $user, string $locale): string
    {
        $tenantIds = [];
        $primaryTenantId = (int) ($user['primary_tenant_id'] ?? 0);
        $currentTenantId = (int) ($user['current_tenant_id'] ?? 0);
        if ($primaryTenantId > 0) {
            $tenantIds[] = $primaryTenantId;
        }
        if ($currentTenantId > 0 && $currentTenantId !== $primaryTenantId) {
            $tenantIds[] = $currentTenantId;
        }

        $userId = (int) ($user['id'] ?? 0);
        if (!$tenantIds && $userId > 0) {
            $tenantIds = array_values(array_map(
                'intval',
                $this->userTenantRepository->listTenantIdsByUserId($userId)
            ));
        }

        foreach ($tenantIds as $tenantId) {
            if ($tenantId <= 0) {
                continue;
            }
            $tenant = $this->userDirectoryGateway->findTenant($tenantId);
            if (!$tenant || (string) ($tenant['status'] ?? 'active') !== 'active') {
                continue;
            }
            $tenantSlug = $this->tenantSsoService->tenantLoginSlug($tenant);
            if ($tenantSlug !== '') {
                return appUrl(Request::withLocale('login?tenant=' . rawurlencode($tenantSlug), $locale));
            }
        }

        return appUrl(Request::withLocale('login', $locale));
    }
}
