<?php

declare(strict_types=1);

namespace ApiModel\Infrastructure\Persistence\Repositories;

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

final class PdoBranchRepository implements BranchRepositoryInterface
{
    public function __construct(private readonly PDO $pdo) {}

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

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

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

        return $st->fetchAll();
    }

    public function insert(
        string $id,
        string $companyId,
        string $name,
        ?string $code,
        ?string $address,
        ?string $phone,
        bool $isMain,
        string $operatingCurrency
    ): void {
        if ($isMain) {
            $this->pdo->prepare('UPDATE branches SET is_main = FALSE WHERE company_id = ?')->execute([$companyId]);
        }

        $this->pdo->prepare(
            'INSERT INTO branches (id, company_id, name, code, address, phone, is_main, operating_currency, is_active)
             VALUES (?, ?, ?, ?, ?, ?, ?, ?, TRUE)'
        )->execute([$id, $companyId, $name, $code, $address, $phone, Database::bool($isMain), $operatingCurrency]);
    }

    public function update(
        string $id,
        string $name,
        ?string $code,
        ?string $address,
        ?string $phone,
        bool $isMain,
        bool $isActive,
        string $operatingCurrency
    ): void {
        $branch = $this->findById($id);
        if ($branch === null) {
            return;
        }

        if ($isMain) {
            $this->pdo->prepare('UPDATE branches SET is_main = FALSE WHERE company_id = ?')->execute([$branch['company_id']]);
        }

        $this->pdo->prepare(
            'UPDATE branches
             SET name = ?, code = ?, address = ?, phone = ?, is_main = ?, operating_currency = ?, is_active = ?, updated_at = CURRENT_TIMESTAMP
             WHERE id = ?'
        )->execute([$name, $code, $address, $phone, Database::bool($isMain), $operatingCurrency, Database::bool($isActive), $id]);
    }

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