<?php

namespace App\Service;

use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Address;

/**
 * Envoi des emails de rapport de scan (avec pièce jointe Excel) et d'erreur.
 * Port de app/api/send-report/route.ts.
 */
final class ReportMailer
{
    private const XLSX_CONTENT_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';

    public function __construct(
        private readonly MailerInterface $mailer,
        private readonly XlsxReportBuilder $xlsx,
        #[Autowire('%env(MAILER_FROM_EMAIL)%')]
        private readonly string $fromEmail,
        #[Autowire('%env(MAILER_FROM_NAME)%')]
        private readonly string $fromName,
    ) {
    }

    /**
     * @param array<int, array<string, mixed>> $results
     * @param list<string>                     $concessions
     */
    public function sendReport(string $to, array $results, string $label, array $concessions, ?string $locationNote = null): void
    {
        $concessionStr = [] !== $concessions ? implode(' / ', $concessions) : '-';
        // L'auteur du scan = le destinataire (on envoie le rapport à soi-même).
        $content = $this->xlsx->build($results, $concessionStr, $locationNote, $to);
        $count = \count($results);
        $filename = sprintf('scan-vehicules-%s.xlsx', date('Y-m-d'));

        $email = (new TemplatedEmail())
            ->from(new Address($this->fromEmail, $this->fromName))
            ->to($to)
            ->subject(sprintf('Scan Inventaire — Rapport de scan (%d véhicule%s)', $count, $count > 1 ? 's' : ''))
            ->htmlTemplate('email/report.html.twig')
            ->context(['label' => $label, 'count' => $count]);

        $email->attach($content, $filename, self::XLSX_CONTENT_TYPE);

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

    public function sendError(string $to, string $errorLog): void
    {
        $email = (new TemplatedEmail())
            ->from(new Address($this->fromEmail, $this->fromName))
            ->to($to)
            ->subject('Scan Inventaire — Erreur lors du scan')
            ->htmlTemplate('email/report_error.html.twig')
            ->context(['errorLog' => $errorLog]);

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