<?php

declare(strict_types=1);

namespace App\Module\Absence\Infrastructure\Controller;

use App\Module\Absence\Domain\Repository\AbsenceRequestRepositoryInterface;
use DateTimeImmutable;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;

/**
 * Admin calendar view: all pending/approved absences overlapping a date range.
 */
class AbsenceCalendarController extends AbstractController
{
    public function __construct(
        private readonly AbsenceRequestRepositoryInterface $requestRepository,
    ) {}

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

        if ('' === $fromRaw || '' === $toRaw) {
            throw new UnprocessableEntityHttpException('Query parameters "from" and "to" are required.');
        }

        $from = new DateTimeImmutable($fromRaw);
        $to   = new DateTimeImmutable($toRaw);

        $absences = $this->requestRepository->findInRange($from, $to);

        return $this->json($absences, context: ['groups' => ['absence_request:read']]);
    }
}
