<?php

declare(strict_types=1);

namespace ApiModel\Infrastructure\Persistence\Repositories;

use ApiModel\Domain\Repository\PagoFerreteriaRepositoryInterface;
use PDO;

final class PdoPagoFerreteriaRepository implements PagoFerreteriaRepositoryInterface
{
    public function __construct(private readonly PDO $pdo) {}

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

    public function insert(
        string $id,
        string $ferreteriaId,
        float $monto,
        string $fechaPago,
        ?string $referencia,
        ?string $descripcion,
        ?string $registradoPor
    ): void {
        $st = $this->pdo->prepare(
            'INSERT INTO public.pagos_ferreterias (id, ferreteria_id, monto, fecha_pago, referencia, descripcion, registrado_por)
             VALUES (?, ?, ?, ?, ?, ?, ?)'
        );
        $st->execute([$id, $ferreteriaId, $monto, $fechaPago, $referencia, $descripcion, $registradoPor]);
    }

    public function listAll(): array
    {
        $st = $this->pdo->query('
            SELECT p.*, f.nombre as ferreteria_nombre, u.name as registrado_por_nombre 
            FROM public.pagos_ferreterias p
            JOIN public.ferreterias f ON f.id = p.ferreteria_id
            LEFT JOIN auth.users u ON u.id = p.registrado_por
            ORDER BY p.created_at DESC
        ');
        return $st->fetchAll();
    }

    public function listAllByFerreteria(string $ferreteriaId): array
    {
        $st = $this->pdo->prepare('
            SELECT p.*, f.nombre as ferreteria_nombre, u.name as registrado_por_nombre 
            FROM public.pagos_ferreterias p
            JOIN public.ferreterias f ON f.id = p.ferreteria_id
            LEFT JOIN auth.users u ON u.id = p.registrado_por
            WHERE p.ferreteria_id = ?
            ORDER BY p.created_at DESC
        ');
        $st->execute([$ferreteriaId]);
        return $st->fetchAll();
    }

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