<?php

declare(strict_types=1);

namespace App\SuperAdmin\Infrastructure\Api\Provider;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\SuperAdmin\Domain\Model\Establishment\EstablishmentId;
use App\SuperAdmin\Domain\Repository\EstablishmentRepository;
use App\SuperAdmin\Infrastructure\Api\Resource\EstablishmentResource;
use Override;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Throwable;

/**
 * @implements ProviderInterface<EstablishmentResource>
 */
final readonly class EstablishmentItemProvider implements ProviderInterface
{
    public function __construct(
        private EstablishmentRepository $establishmentRepository,
    ) {
    }

    #[Override]
    public function provide(Operation $operation, array $uriVariables = [], array $context = []): EstablishmentResource
    {
        /** @var string $id */
        $id = $uriVariables['id'] ?? throw new NotFoundHttpException();

        try {
            $establishment = $this->establishmentRepository->get(
                EstablishmentId::fromString($id),
            );
        } catch (Throwable) {
            throw new NotFoundHttpException();
        }

        $resource = new EstablishmentResource();
        $resource->id = (string) $establishment->id;
        $resource->tenantId = (string) $establishment->tenantId;
        $resource->name = $establishment->name;
        $resource->subdomain = $establishment->subdomain;
        $resource->databaseName = $establishment->databaseName;
        $resource->status = $establishment->status->value;
        $resource->createdAt = $establishment->createdAt->format('c');
        $resource->lastActivityAt = $establishment->lastActivityAt?->format('c');

        return $resource;
    }
}
