<?php

declare(strict_types=1);

namespace ApiModel\Infrastructure\Persistence\Repositories;

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

final class PdoDepartmentRepository implements DepartmentRepositoryInterface
{
    public function __construct(private readonly PDO $pdo) {}

    public function findById(string $id): ?array
    {
        $st = $this->pdo->prepare('SELECT * FROM hr.departments 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 hr.departments WHERE company_id = ? ORDER BY name ASC'
        );
        $st->execute([$companyId]);

        return $st->fetchAll();
    }

    public function insert(string $id, string $companyId, string $name): void
    {
        $st = $this->pdo->prepare(
            'INSERT INTO hr.departments (id, company_id, name, is_active)
             VALUES (?, ?, ?, TRUE)'
        );
        $st->execute([$id, $companyId, $name]);
    }

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

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