<?php

namespace App\Service;

use Symfony\Component\DependencyInjection\Attribute\Autowire;

/**
 * Restriction des emails aux domaines autorisés (Emil Frey / Autosphere).
 * Port de ALLOWED_DOMAINS / isEmailAllowed de lib/auth.ts.
 */
final class EmailDomainPolicy
{
    /** @var list<string> */
    private array $allowedDomains;

    public function __construct(
        #[Autowire('%env(ALLOWED_EMAIL_DOMAINS)%')]
        string $allowedDomains,
    ) {
        $this->allowedDomains = array_values(array_filter(array_map(
            static fn (string $d) => strtolower(trim($d)),
            explode(',', $allowedDomains)
        )));
    }

    public function isAllowed(string $email): bool
    {
        $parts = explode('@', strtolower(trim($email)));
        $domain = $parts[1] ?? null;

        return null !== $domain && in_array($domain, $this->allowedDomains, true);
    }

    /** @return list<string> */
    public function allowedDomains(): array
    {
        return $this->allowedDomains;
    }
}
