<?php

declare(strict_types=1);

namespace App\Scolarite\Infrastructure\Api\Provider;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\Administration\Domain\Model\User\Role;
use App\Administration\Infrastructure\Security\SecurityUser;
use App\Scolarite\Application\Query\GetHomeworkExceptionsReport\GetHomeworkExceptionsReportHandler;
use App\Scolarite\Application\Query\GetHomeworkExceptionsReport\GetHomeworkExceptionsReportQuery;
use App\Scolarite\Application\Query\GetHomeworkExceptionsReport\HomeworkExceptionDto;
use App\Scolarite\Infrastructure\Api\Resource\HomeworkExceptionResource;
use App\Shared\Infrastructure\Tenant\TenantContext;

use function array_map;
use function in_array;
use function is_string;

use Override;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;

/**
 * @implements ProviderInterface<HomeworkExceptionResource>
 */
final readonly class HomeworkExceptionsReportProvider implements ProviderInterface
{
    public function __construct(
        private GetHomeworkExceptionsReportHandler $handler,
        private TenantContext $tenantContext,
        private RequestStack $requestStack,
        private Security $security,
    ) {
    }

    /** @return array<HomeworkExceptionResource> */
    #[Override]
    public function provide(Operation $operation, array $uriVariables = [], array $context = []): array
    {
        if (!$this->tenantContext->hasTenant()) {
            throw new UnauthorizedHttpException('Bearer', 'Tenant non défini.');
        }

        $user = $this->security->getUser();

        if (!$user instanceof SecurityUser) {
            throw new UnauthorizedHttpException('Bearer', 'Authentification requise.');
        }

        if (!in_array(Role::ADMIN->value, $user->getRoles(), true)
            && !in_array(Role::SUPER_ADMIN->value, $user->getRoles(), true)) {
            throw new AccessDeniedHttpException('Accès réservé à la direction.');
        }

        $request = $this->requestStack->getCurrentRequest();
        $startDate = $request?->query->get('startDate');
        $endDate = $request?->query->get('endDate');
        $teacherId = $request?->query->get('teacherId');
        $ruleType = $request?->query->get('ruleType');

        $query = new GetHomeworkExceptionsReportQuery(
            tenantId: (string) $this->tenantContext->getCurrentTenantId(),
            startDate: is_string($startDate) ? $startDate : null,
            endDate: is_string($endDate) ? $endDate : null,
            teacherId: is_string($teacherId) ? $teacherId : null,
            ruleType: is_string($ruleType) ? $ruleType : null,
        );

        $dtos = ($this->handler)($query);

        return array_map(
            static function (HomeworkExceptionDto $dto): HomeworkExceptionResource {
                $resource = new HomeworkExceptionResource();
                $resource->id = $dto->id;
                $resource->homeworkId = $dto->homeworkId;
                $resource->homeworkTitle = $dto->homeworkTitle;
                $resource->ruleType = $dto->ruleType;
                $resource->justification = $dto->justification;
                $resource->teacherId = $dto->teacherId;
                $resource->teacherName = $dto->teacherName;
                $resource->createdAt = $dto->createdAt;

                return $resource;
            },
            $dtos,
        );
    }
}
