<?php

declare(strict_types=1);

namespace App\SuperAdmin\Infrastructure\Api\Processor;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\SuperAdmin\Application\Command\CreateEstablishment\CreateEstablishmentCommand;
use App\SuperAdmin\Application\Command\CreateEstablishment\CreateEstablishmentHandler;
use App\SuperAdmin\Infrastructure\Api\Resource\EstablishmentResource;
use App\SuperAdmin\Infrastructure\Security\SecuritySuperAdmin;
use Override;
use Symfony\Bundle\SecurityBundle\Security;

/**
 * @implements ProcessorInterface<EstablishmentResource, EstablishmentResource>
 */
final readonly class CreateEstablishmentProcessor implements ProcessorInterface
{
    public function __construct(
        private CreateEstablishmentHandler $handler,
        private Security $security,
    ) {
    }

    /**
     * @param EstablishmentResource $data
     */
    #[Override]
    public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): EstablishmentResource
    {
        /** @var SecuritySuperAdmin $user */
        $user = $this->security->getUser();

        $result = ($this->handler)(new CreateEstablishmentCommand(
            name: $data->name,
            subdomain: $data->subdomain,
            adminEmail: $data->adminEmail,
            superAdminId: $user->superAdminId(),
        ));

        $resource = new EstablishmentResource();
        $resource->id = $result->establishmentId;
        $resource->tenantId = $result->tenantId;
        $resource->name = $result->name;
        $resource->subdomain = $result->subdomain;
        $resource->databaseName = $result->databaseName;
        $resource->status = 'active';

        return $resource;
    }
}
