<?php

declare(strict_types=1);

namespace ApiModel\Infrastructure\Persistence\Repositories;

use ApiModel\Domain\Repository\LeaveRepositoryInterface;
use PDO;

final class PdoLeaveRepository implements LeaveRepositoryInterface
{
    public function __construct(private readonly PDO $pdo) {}

    public function findById(string $id): ?array
    {
        $st = $this->pdo->prepare(
            'SELECT l.*, e.first_name, e.last_name, e.identification_number
             FROM hr.leaves l
             JOIN hr.employees e ON l.employee_id = e.id
             WHERE l.id = ?
             LIMIT 1'
        );
        $st->execute([$id]);
        $row = $st->fetch();

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

    public function listByCompany(string $companyId): array
    {
        $st = $this->pdo->prepare(
            'SELECT l.*, e.first_name, e.last_name, e.identification_number, d.name as department_name
             FROM hr.leaves l
             JOIN hr.employees e ON l.employee_id = e.id
             LEFT JOIN hr.departments d ON e.department_id = d.id
             WHERE e.company_id = ?
             ORDER BY l.start_date DESC, l.created_at DESC'
        );
        $st->execute([$companyId]);

        return $st->fetchAll();
    }

    public function insert(array $leave): void
    {
        $st = $this->pdo->prepare(
            'INSERT INTO hr.leaves (
                id, employee_id, leave_type, start_date, end_date, status, notes
             ) VALUES (
                :id, :employee_id, :leave_type, :start_date, :end_date, :status, :notes
             )'
        );
        $st->execute([
            'id' => $leave['id'],
            'employee_id' => $leave['employee_id'],
            'leave_type' => $leave['leave_type'],
            'start_date' => $leave['start_date'],
            'end_date' => $leave['end_date'],
            'status' => $leave['status'] ?: 'pending',
            'notes' => $leave['notes'] ?: null,
        ]);
    }

    public function update(string $id, array $leave): void
    {
        $st = $this->pdo->prepare(
            'UPDATE hr.leaves SET
                employee_id = :employee_id,
                leave_type = :leave_type,
                start_date = :start_date,
                end_date = :end_date,
                status = :status,
                notes = :notes,
                updated_at = CURRENT_TIMESTAMP
             WHERE id = :id'
        );
        $st->execute([
            'id' => $id,
            'employee_id' => $leave['employee_id'],
            'leave_type' => $leave['leave_type'],
            'start_date' => $leave['start_date'],
            'end_date' => $leave['end_date'],
            'status' => $leave['status'],
            'notes' => $leave['notes'] ?: null,
        ]);
    }

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