<?php

declare(strict_types=1);

namespace App\Administration\Infrastructure\Api\Processor;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\Administration\Application\Command\UpdateImageRights\UpdateImageRightsCommand;
use App\Administration\Application\Command\UpdateImageRights\UpdateImageRightsHandler;
use App\Administration\Domain\Exception\UserNotFoundException;
use App\Administration\Infrastructure\Api\Resource\ImageRightsResource;
use App\Administration\Infrastructure\Security\ImageRightsVoter;
use App\Administration\Infrastructure\Security\SecurityUser;
use App\Shared\Application\Port\AuditLogger;
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\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use ValueError;

/**
 * @implements ProcessorInterface<ImageRightsResource, ImageRightsResource>
 */
final readonly class UpdateImageRightsProcessor implements ProcessorInterface
{
    public function __construct(
        private UpdateImageRightsHandler $handler,
        private MessageBusInterface $eventBus,
        private AuthorizationCheckerInterface $authorizationChecker,
        private TenantContext $tenantContext,
        private Security $security,
        private AuditLogger $auditLogger,
    ) {
    }

    /**
     * @param ImageRightsResource $data
     */
    #[Override]
    public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): ImageRightsResource
    {
        if (!$this->authorizationChecker->isGranted(ImageRightsVoter::EDIT)) {
            throw new AccessDeniedHttpException('Vous n\'êtes pas autorisé à modifier les droits à l\'image.');
        }

        if (!$this->tenantContext->hasTenant()) {
            throw new UnauthorizedHttpException('Bearer', 'Tenant non défini.');
        }

        /** @var string $studentId */
        $studentId = $uriVariables['id'] ?? '';
        $status = $data->imageRightsStatus ?? '';

        if ($status === '') {
            throw new BadRequestHttpException('Le statut du droit à l\'image est obligatoire.');
        }

        $currentUser = $this->security->getUser();
        if (!$currentUser instanceof SecurityUser) {
            throw new UnauthorizedHttpException('Bearer', 'Utilisateur non authentifié.');
        }

        try {
            $command = new UpdateImageRightsCommand(
                studentId: $studentId,
                status: $status,
                modifiedBy: $currentUser->userId(),
                tenantId: (string) $this->tenantContext->getCurrentTenantId(),
            );
            $user = ($this->handler)($command);

            /** @var ImageRightsResource $previousData */
            $previousData = $context['previous_data'];
            $oldStatus = $previousData->imageRightsStatus;

            $this->auditLogger->logDataChange(
                aggregateType: 'User',
                aggregateId: $user->id->value,
                eventType: 'ImageRightsUpdated',
                oldValues: ['image_rights_status' => $oldStatus],
                newValues: ['image_rights_status' => $status],
                reason: 'Mise à jour du droit à l\'image',
            );

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

            $resource = new ImageRightsResource();
            $resource->id = (string) $user->id;
            $resource->firstName = $user->firstName;
            $resource->lastName = $user->lastName;
            $resource->email = (string) $user->email;
            $resource->imageRightsStatus = $user->imageRightsStatus->value;
            $resource->imageRightsStatusLabel = $user->imageRightsStatus->label();
            $resource->imageRightsUpdatedAt = $user->imageRightsUpdatedAt;

            return $resource;
        } catch (UserNotFoundException $e) {
            throw new NotFoundHttpException($e->getMessage());
        } catch (ValueError $e) {
            throw new BadRequestHttpException('Statut de droit à l\'image invalide : ' . $e->getMessage());
        }
    }
}
