<?php

declare(strict_types=1);

namespace ApiModel\Infrastructure\Persistence\Repositories;

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

final class PdoTaxRateRepository implements TaxRateRepositoryInterface
{
    public function __construct(private readonly PDO $pdo) {}

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

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

    public function findByName(string $companyId, string $name): ?array
    {
        $st = $this->pdo->prepare('SELECT * FROM tax_rates WHERE company_id = ? AND name = ?');
        $st->execute([$companyId, $name]);
        $row = $st->fetch();

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

    public function listByCompany(string $companyId): array
    {
        $st = $this->pdo->prepare(
            'SELECT * FROM tax_rates WHERE company_id = ? ORDER BY rate ASC, name ASC'
        );
        $st->execute([$companyId]);

        return $st->fetchAll();
    }

    public function insert(
        string $id,
        string $companyId,
        string $name,
        float $rate,
        string $type
    ): void {
        $this->pdo->prepare(
            'INSERT INTO tax_rates (id, company_id, name, rate, type, is_active)
             VALUES (?, ?, ?, ?, ?, TRUE)'
        )->execute([$id, $companyId, $name, $rate, $type]);
    }

    public function update(
        string $id,
        string $name,
        float $rate,
        string $type,
        bool $isActive
    ): void {
        $this->pdo->prepare(
            'UPDATE tax_rates
             SET name = ?, rate = ?, type = ?, is_active = ?, updated_at = CURRENT_TIMESTAMP
             WHERE id = ?'
        )->execute([$name, $rate, $type, Database::bool($isActive), $id]);
    }

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