<?php

declare(strict_types=1);

namespace App\Module\Absence\Infrastructure\Controller;

use App\Module\Absence\Domain\Service\PublicHolidayProvider;
use DateTimeImmutable;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;

/**
 * Exposes French public holidays so the front (calendar, date pickers) can
 * display them — the dates are computed server-side in pure PHP.
 */
class PublicHolidayController extends AbstractController
{
    public function __construct(
        private readonly PublicHolidayProvider $holidayProvider,
    ) {}

    #[Route('/api/public_holidays', name: 'public_holidays', methods: ['GET'], priority: 1)]
    #[IsGranted('ROLE_USER')]
    public function __invoke(Request $request): JsonResponse
    {
        $fromRaw = (string) $request->query->get('from', '');
        $toRaw   = (string) $request->query->get('to', '');

        if ('' !== $fromRaw && '' !== $toRaw) {
            $fromYear = (int) new DateTimeImmutable($fromRaw)->format('Y');
            $toYear   = (int) new DateTimeImmutable($toRaw)->format('Y');
        } else {
            $fromYear = $toYear = (int) ($request->query->get('year') ?: date('Y'));
        }

        $holidays = [];
        for ($year = $fromYear; $year <= $toYear; ++$year) {
            $holidays += $this->holidayProvider->getHolidays($year);
        }

        return $this->json($holidays);
    }
}
