<?php

declare(strict_types=1);

namespace App\Administration\Infrastructure\Api\Processor;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\Administration\Application\Command\UpdateHomeworkRules\UpdateHomeworkRulesCommand;
use App\Administration\Application\Command\UpdateHomeworkRules\UpdateHomeworkRulesHandler;
use App\Administration\Domain\Exception\HomeworkRuleParamsInvalidException;
use App\Administration\Infrastructure\Api\Resource\HomeworkRulesResource;
use App\Administration\Infrastructure\Security\SecurityUser;
use App\Shared\Infrastructure\Tenant\TenantContext;
use Override;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Symfony\Component\Messenger\MessageBusInterface;
use ValueError;

/**
 * Processor pour la mise à jour des règles de devoirs.
 *
 * @implements ProcessorInterface<HomeworkRulesResource, HomeworkRulesResource>
 */
final readonly class UpdateHomeworkRulesProcessor implements ProcessorInterface
{
    public function __construct(
        private UpdateHomeworkRulesHandler $handler,
        private TenantContext $tenantContext,
        private MessageBusInterface $eventBus,
        private Security $security,
    ) {
    }

    /**
     * @param HomeworkRulesResource $data
     */
    #[Override]
    public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): HomeworkRulesResource
    {
        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 (!$this->security->isGranted('ROLE_ADMIN')) {
            throw new AccessDeniedHttpException('Seuls les administrateurs peuvent modifier les règles de devoirs.');
        }

        try {
            $command = new UpdateHomeworkRulesCommand(
                tenantId: (string) $this->tenantContext->getCurrentTenantId(),
                rules: $data->rules ?? [],
                enforcementMode: $data->enforcementMode ?? 'soft',
                enabled: $data->enabled ?? true,
                changedBy: $user->userId(),
            );

            $homeworkRules = ($this->handler)($command);

            foreach ($homeworkRules->pullDomainEvents() as $event) {
                $this->eventBus->dispatch($event);
            }

            return HomeworkRulesResource::fromDomain($homeworkRules);
        } catch (HomeworkRuleParamsInvalidException|ValueError $e) {
            throw new BadRequestHttpException($e->getMessage());
        }
    }
}
