<?php

declare(strict_types=1);

namespace ApiModel\Infrastructure\Persistence\Repositories;

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

final class PdoModuleRepository implements ModuleRepositoryInterface
{
    public function __construct(private readonly PDO $pdo) {}

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

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

    public function insert(string $id, string $nameEs, string $nameEn, ?string $icon, int $orderIndex): void
    {
        $this->pdo->prepare(
            'INSERT INTO auth.module (id, name_es, name_en, icon, order_index, is_active)
             VALUES (?, ?, ?, ?, ?, TRUE)'
        )->execute([$id, $nameEs, $nameEn, $icon, $orderIndex]);
    }

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

    public function listActive(): array
    {
        $st = $this->pdo->query('SELECT * FROM auth.module WHERE is_active = TRUE ORDER BY order_index ASC, name_es ASC');
        return $st->fetchAll();
    }

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

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