<?php

namespace App\Service;

use App\Entity\User;
use App\Repository\UserRepository;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Address;

/**
 * Notifie les valideurs (ADMIN_EMAILS + utilisateurs ADMIN/AUDIT actifs) d'une nouvelle demande d'accès.
 */
final class UserValidationMailer
{
    /** @var list<string> */
    private array $adminEmails;

    public function __construct(
        private readonly MailerInterface $mailer,
        private readonly UserRepository $users,
        private readonly ConcessionsProvider $concessions,
        #[Autowire('%env(MAILER_FROM_EMAIL)%')]
        private readonly string $fromEmail,
        #[Autowire('%env(MAILER_FROM_NAME)%')]
        private readonly string $fromName,
        #[Autowire('%env(ADMIN_EMAILS)%')]
        string $adminEmails = '',
    ) {
        $this->adminEmails = array_values(array_filter(array_map(
            static fn (string $e) => strtolower(trim($e)),
            explode(',', $adminEmails)
        )));
    }

    public function sendValidationRequest(User $requester, string $validationUrl): void
    {
        $recipients = array_values(array_unique(array_merge(
            $this->adminEmails,
            $this->users->findValidatorEmails(),
        )));
        if ([] === $recipients) {
            return;
        }

        $email = (new TemplatedEmail())
            ->from(new Address($this->fromEmail, $this->fromName))
            ->subject('Scan Inventaire — Nouvelle demande d\'accès à valider')
            ->htmlTemplate('email/user_validation_request.html.twig')
            ->context([
                'requesterEmail' => $requester->getUserIdentifier(),
                'requestedRoleLabel' => User::GROUP_LABELS[$requester->getRequestedRole()] ?? ($requester->getRequestedRole() ?? '—'),
                'concessions' => $this->concessions->names($requester->getConcessions()),
                'validationUrl' => $validationUrl,
            ]);

        foreach ($recipients as $to) {
            $email->addTo($to);
        }

        $this->mailer->send($email);
    }

    /**
     * Notifie l'utilisateur que sa demande d'accès a été validée (groupe + concessions attribués).
     */
    public function sendAccessGranted(User $user, string $loginUrl): void
    {
        $email = (new TemplatedEmail())
            ->from(new Address($this->fromEmail, $this->fromName))
            ->to($user->getUserIdentifier())
            ->subject('Scan Inventaire — Votre accès est validé')
            ->htmlTemplate('email/user_access_granted.html.twig')
            ->context([
                'userEmail' => $user->getUserIdentifier(),
                'groupLabel' => $user->getGroupLabel(),
                'concessions' => $this->concessions->names($user->getConcessions()),
                'loginUrl' => $loginUrl,
            ]);

        $this->mailer->send($email);
    }
}
