<?php

declare(strict_types=1);

namespace ApiModel\Infrastructure\Persistence\Repositories;

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

final class PdoPageRepository implements PageRepositoryInterface
{
    public function __construct(private readonly PDO $pdo) {}

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

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

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

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

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

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

    public function listActiveByModule(string $moduleId): array
    {
        $st = $this->pdo->prepare('SELECT * FROM auth.page WHERE module_id = ? AND is_active = TRUE ORDER BY order_index ASC, name_es ASC');
        $st->execute([$moduleId]);
        return $st->fetchAll();
    }

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

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