<?php

declare(strict_types=1);

namespace App\Scolarite\Infrastructure\Service;

use App\Scolarite\Application\Port\PeriodFinder;
use App\Scolarite\Application\Port\PeriodInfo;
use App\Shared\Domain\Tenant\TenantId;
use DateTimeImmutable;
use Doctrine\DBAL\Connection;
use Override;

final readonly class DoctrinePeriodFinder implements PeriodFinder
{
    public function __construct(
        private Connection $connection,
    ) {
    }

    #[Override]
    public function findForDate(DateTimeImmutable $date, TenantId $tenantId): ?PeriodInfo
    {
        $row = $this->connection->fetchAssociative(
            'SELECT id, start_date, end_date
             FROM academic_periods
             WHERE tenant_id = :tenant_id
             AND start_date <= :date
             AND end_date >= :date
             ORDER BY start_date DESC
             LIMIT 1',
            [
                'tenant_id' => (string) $tenantId,
                'date' => $date->format('Y-m-d'),
            ],
        );

        if ($row === false) {
            return null;
        }

        /** @var string $id */
        $id = $row['id'];
        /** @var string $startDate */
        $startDate = $row['start_date'];
        /** @var string $endDate */
        $endDate = $row['end_date'];

        return new PeriodInfo(
            periodId: $id,
            startDate: new DateTimeImmutable($startDate),
            endDate: new DateTimeImmutable($endDate),
        );
    }
}
