<?php

declare(strict_types=1);

namespace ApiModel\Infrastructure\Persistence\Repositories;

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

final class PdoContactRepository implements ContactRepositoryInterface
{
    public function __construct(private readonly PDO $pdo) {}

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

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

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

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

    public function listByCompany(string $companyId, ?string $type = null): array
    {
        if ($type !== null) {
            $st = $this->pdo->prepare(
                'SELECT * FROM contacts WHERE company_id = ? AND (type = ? OR type = \'both\') ORDER BY name ASC'
            );
            $st->execute([$companyId, $type]);
        } else {
            $st = $this->pdo->prepare(
                'SELECT * FROM contacts WHERE company_id = ? ORDER BY name ASC'
            );
            $st->execute([$companyId]);
        }

        return $st->fetchAll();
    }

    public function insert(
        string $id,
        string $companyId,
        string $type,
        string $name,
        ?string $taxId,
        ?string $email,
        ?string $phone,
        ?string $address
    ): void {
        $this->pdo->prepare(
            'INSERT INTO contacts (id, company_id, type, name, tax_id, email, phone, address, is_active)
             VALUES (?, ?, ?, ?, ?, ?, ?, ?, TRUE)'
        )->execute([$id, $companyId, $type, $name, $taxId, $email, $phone, $address]);
    }

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

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