<?php

declare(strict_types=1);

namespace ApiModel\Infrastructure\Persistence\Repositories;

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

final class PdoRoleRepository implements RoleRepositoryInterface
{
    public function __construct(private readonly PDO $pdo) {}

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

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

    public function findByName(string $nameEsOrEn): ?array
    {
        $st = $this->pdo->prepare('SELECT * FROM auth.roles WHERE name_es = ? OR name_en = ?');
        $st->execute([$nameEsOrEn, $nameEsOrEn]);
        $row = $st->fetch();

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

    public function insert(string $id, string $nameEs, string $nameEn, ?string $descEs, ?string $descEn): void
    {
        $this->pdo->prepare(
            'INSERT INTO auth.roles (id, name_es, name_en, description_es, description_en, is_active)
             VALUES (?, ?, ?, ?, ?, TRUE)'
        )->execute([$id, $nameEs, $nameEn, $descEs, $descEn]);
    }

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

    public function update(string $id, string $nameEs, string $nameEn, ?string $descEs, ?string $descEn, bool $isActive): void
    {
        $this->pdo->prepare(
            'UPDATE auth.roles 
             SET name_es = ?, name_en = ?, description_es = ?, description_en = ?, is_active = ?, updated_at = CURRENT_TIMESTAMP
             WHERE id = ?'
        )->execute([$nameEs, $nameEn, $descEs, $descEn, Database::bool($isActive), $id]);
    }

    public function delete(string $id): void
    {
        $this->pdo->prepare('DELETE FROM auth.roles WHERE id = ?')->execute([$id]);
    }
}
