<?php

declare(strict_types=1);

namespace App\Services;

use App\Models\MailTemplate;

final class MailTemplateService extends BaseService
{
    private const ALLOWED_TYPES = ['DEVIS', 'FACTURE'];

    public function __construct(
        private readonly MailTemplate $templates = new MailTemplate()
    ) {
    }

    /** @return array<int,array<string,mixed>> */
    public function all(): array
    {
        return $this->templates->all();
    }

    /** @param array<string,mixed> $document @return array<string,string> */
    public function render(string $type, array $document): array
    {
        $type = $this->normalizeType($type);
        $template = $this->templates->findByType($type);

        if ($template === null || (int)($template['actif'] ?? 0) !== 1) {
            throw new \RuntimeException(
                'Aucun modèle d’e-mail actif n’est configuré pour ce document.'
            );
        }

        $societe = (new ParametreSocieteService())->get();
        $clientName = trim((string)($document['client_nom'] ?? ''));

        $replacements = [
            '{NUMERO}' => trim((string)($document['numero'] ?? '')),
            '{CLIENT}' => $clientName !== '' ? $clientName : 'Madame, Monsieur',
            '{SOCIETE}' => trim((string)(
                $societe['nom_commercial']
                ?? $societe['raison_sociale']
                ?? 'Darlink ERP'
            )),
        ];

        return [
            'name' => (string)($template['nom'] ?? ''),
            'subject' => strtr((string)$template['objet'], $replacements),
            'message' => strtr((string)$template['contenu_html'], $replacements),
            'text' => strtr(
                (string)($template['contenu_texte'] ?: $template['contenu_html']),
                $replacements
            ),
        ];
    }

    /** @param array<string,mixed> $data */
    public function save(array $data): void
    {
        $type = $this->normalizeType((string)($data['type_document'] ?? ''));
        $name = trim((string)($data['nom'] ?? ''));
        $subject = trim((string)($data['objet'] ?? ''));
        $body = trim((string)($data['contenu_html'] ?? ''));

        if ($name === '' || $subject === '' || $body === '') {
            throw new \InvalidArgumentException(
                'Le nom, l’objet et le message du modèle sont obligatoires.'
            );
        }

        $this->templates->save([
            'type_document' => $type,
            'nom' => $name,
            'objet' => $subject,
            'contenu_html' => $body,
            'contenu_texte' => trim((string)($data['contenu_texte'] ?? '')),
            'actif' => !empty($data['actif']) ? 1 : 0,
        ]);
    }

    private function normalizeType(string $type): string
    {
        $type = strtoupper(trim($type));

        if (!in_array($type, self::ALLOWED_TYPES, true)) {
            throw new \InvalidArgumentException('Type de modèle e-mail invalide.');
        }

        return $type;
    }
}
