<?php

declare(strict_types=1);

namespace App\SuperAdmin\Application\Command\CreateEstablishment;

use App\Shared\Domain\Clock;
use App\SuperAdmin\Domain\Model\Establishment\Establishment;
use App\SuperAdmin\Domain\Model\SuperAdmin\SuperAdminId;
use App\SuperAdmin\Domain\Repository\EstablishmentRepository;

final readonly class CreateEstablishmentHandler
{
    public function __construct(
        private EstablishmentRepository $establishmentRepository,
        private Clock $clock,
    ) {
    }

    public function __invoke(CreateEstablishmentCommand $command): CreateEstablishmentResult
    {
        $establishment = Establishment::creer(
            name: $command->name,
            subdomain: $command->subdomain,
            createdBy: SuperAdminId::fromString($command->superAdminId),
            createdAt: $this->clock->now(),
        );

        $this->establishmentRepository->save($establishment);

        return new CreateEstablishmentResult(
            establishmentId: (string) $establishment->id,
            tenantId: (string) $establishment->tenantId,
            name: $establishment->name,
            subdomain: $establishment->subdomain,
            databaseName: $establishment->databaseName,
        );
    }
}
