<?php

declare(strict_types=1);

namespace ApiModel\Infrastructure\Persistence\Repositories;

use ApiModel\Domain\Repository\SecurityMenuRepositoryInterface;
use PDO;

/**
 * Lectura de menú y permisos por usuario desde {@see auth.vsecurity} (PostgreSQL, mismo criterio que api_v1 Auth::Menu_Pages / Menu_Leng).
 */
final class PdoSecurityMenuRepository implements SecurityMenuRepositoryInterface
{
    public function __construct(private readonly PDO $pdo) {}

    public function getPagesForUser(string $userId): array
    {
        $sql = <<<'SQL'
            SELECT pag_name AS name, pag_icon AS icon, '/' || pag_to AS "to",
                   "insert", edit, "delete", plus
            FROM auth.vsecurity
            WHERE id = ? AND activo AND mod_activo AND rol_activo
            GROUP BY pag_name, pag_icon, pag_to, "insert", edit, "delete", plus
            SQL;
        $st = $this->pdo->prepare($sql);
        $st->execute([$userId]);

        return $st->fetchAll(PDO::FETCH_ASSOC);
    }

    public function getMenuForUser(string $userId): array
    {
        $st = $this->pdo->prepare(
            <<<'SQL'
            SELECT DISTINCT pag_name AS label, pag_icon AS icon, pag_to AS "to", pag_orden
            FROM auth.vsecurity
            WHERE id = ? AND activo AND module = 1 AND mod_activo AND rol_activo AND pag_activo
            ORDER BY pag_orden
            SQL,
        );
        $st->execute([$userId]);
        $external = $st->fetchAll(PDO::FETCH_ASSOC);

        $st = $this->pdo->prepare(
            <<<'SQL'
            SELECT DISTINCT module, mod_name AS mod, mod_icon AS icon, ord
            FROM auth.vsecurity
            WHERE id = ? AND activo AND module <> 1 AND mod_activo AND rol_activo AND pag_activo
            ORDER BY ord
            SQL,
        );
        $st->execute([$userId]);
        $consult = $st->fetchAll(PDO::FETCH_ASSOC);

        $internal = [];
        $itemStmt = $this->pdo->prepare(
            <<<'SQL'
            SELECT DISTINCT module, pag_name AS label, pag_icon AS icon, pag_to AS "to", pag_orden
            FROM auth.vsecurity
            WHERE id = ? AND module = ? AND activo AND mod_activo AND rol_activo AND pag_activo
            ORDER BY pag_orden
            SQL,
        );

        foreach ($consult as $i => $row) {
            $internal[$i]['label'] = $row['mod'];
            $internal[$i]['icon'] = $row['icon'];
            $module = $row['module'];
            $itemStmt->execute([$userId, $module]);
            $internal[$i]['items'] = $itemStmt->fetchAll(PDO::FETCH_ASSOC);
        }

        return [
            'external' => $external,
            'internal' => $internal,
        ];
    }
}
