<?php

namespace NoahVet\Reef\Infrastructure\Security\Api;

use NoahVet\Reef\Domain\Security\Model\Resource;
use NoahVet\Reef\Domain\Security\Model\ResourceGroupWithMembers;
use NoahVet\Reef\Domain\Security\Port\ResourceRegistryInterface;
use NoahVet\Reef\Iam\Client;
use NoahVet\Reef\Iam\Exception\BadRequestException;
use Symfony\Component\HttpFoundation\Response;

class JaneResourceRegistry implements ResourceRegistryInterface
{
    public function __construct(
        private readonly Client $iamServiceClient,
    ) {
    }

    #[\Override]
    public function register(Resource|ResourceGroupWithMembers $resource): void
    {
        if ($resource instanceof Resource) {
            $this->registerResource($resource);

            return;
        }

        // @todo Add ResourceGroupWithMembers management
    }

    private function registerResource(Resource $resource): void
    {
        $response = $this->iamServiceClient->executeRawEndpoint(
            new \NoahVet\Reef\Iam\Endpoint\PostResourceCollection(
                (new \NoahVet\Reef\Iam\Model\Resource())
                    ->setSlug($resource->getSlug())
                    ->setResourceType('/api/resource_types/'.$resource->getResourceType()->getSlug()),
            ),
        );

        if (
            !\in_array(
                $response->getStatusCode(),
                [
                    Response::HTTP_OK,
                    Response::HTTP_CREATED,
                    Response::HTTP_CONFLICT,
                    Response::HTTP_UNPROCESSABLE_ENTITY,
                ],
            )
        ) {
            throw new BadRequestException(
                \sprintf(
                    "Can't create resource %s:%s in the IAM. Error code : %s",
                    $resource->getResourceType()->getSlug(),
                    $resource->getResourceId(),
                    $response->getStatusCode(),
                ),
            );
        }
    }
}
