<?php

declare(strict_types=1);

namespace ApiModel\Infrastructure\Persistence\Repositories;

use ApiModel\Domain\Repository\MessageRepositoryInterface;
use ApiModel\Infrastructure\Persistence\Database;
use PDO;

final class PdoMessageRepository implements MessageRepositoryInterface
{
    public function __construct(private readonly PDO $pdo) {}

    public function findByCode(string $code): ?array
    {
        $st = $this->pdo->prepare('SELECT * FROM auth.messages WHERE code = ?');
        $st->execute([$code]);
        $row = $st->fetch();

        return $row !== false ? $row : null;
    }

    public function insert(string $id, string $code, string $subjectEs, string $subjectEn, string $bodyHtmlEs, string $bodyHtmlEn): void
    {
        $this->pdo->prepare(
            'INSERT INTO auth.messages (id, code, subject_es, subject_en, body_html_es, body_html_en, is_active)
             VALUES (?, ?, ?, ?, ?, ?, TRUE)'
        )->execute([$id, $code, $subjectEs, $subjectEn, $bodyHtmlEs, $bodyHtmlEn]);
    }

    public function update(string $id, string $code, string $subjectEs, string $subjectEn, string $bodyHtmlEs, string $bodyHtmlEn, bool $isActive): void
    {
        $this->pdo->prepare(
            'UPDATE auth.messages 
             SET code = ?, subject_es = ?, subject_en = ?, body_html_es = ?, body_html_en = ?, is_active = ?, updated_at = CURRENT_TIMESTAMP
             WHERE id = ?'
        )->execute([$code, $subjectEs, $subjectEn, $bodyHtmlEs, $bodyHtmlEn, Database::bool($isActive), $id]);
    }

    public function listAll(): array
    {
        $st = $this->pdo->query('SELECT * FROM auth.messages ORDER BY code ASC');
        return $st->fetchAll();
    }
}
