<?php

declare(strict_types=1);

namespace ApiModel\Service;

use ApiModel\Domain\Repository\MessageRepositoryInterface;
use ApiModel\Infrastructure\Persistence\Database;
use ApiModel\Shared\Exceptions\NotFoundException;

final class MessageService
{
    public function __construct(private readonly MessageRepositoryInterface $messages) {}

    public function listMessages(): array
    {
        return $this->messages->listAll();
    }

    public function getMessageByCode(string $code): array
    {
        $msg = $this->messages->findByCode($code);
        if (! $msg) {
            throw new NotFoundException('Plantilla no encontrada');
        }
        return $msg;
    }

    public function createMessage(string $code, string $subjectEs, string $subjectEn, string $bodyHtmlEs, string $bodyHtmlEn): array
    {
        $id = Database::uuid();
        $this->messages->insert($id, $code, $subjectEs, $subjectEn, $bodyHtmlEs, $bodyHtmlEn);
        return $this->getMessageByCode($code);
    }

    public function updateMessage(string $id, string $code, string $subjectEs, string $subjectEn, string $bodyHtmlEs, string $bodyHtmlEn, bool $isActive): array
    {
        $this->messages->update($id, $code, $subjectEs, $subjectEn, $bodyHtmlEs, $bodyHtmlEn, $isActive);
        return $this->getMessageByCode($code);
    }
}
