<?php

namespace NoahVet\Reef\Bridge\Reef\IAM\Factory;

use NoahVet\Reef\Bridge\Reef\IAM\Client\ClientAdapter;
use NoahVet\Reef\Jane\Client as JaneClient;
use NoahVet\Reef\Jane\Model\Resource;
use NoahVet\Reef\Jane\Runtime\Client\Client as NoahVetClient;
use Psr\Http\Message\ResponseInterface as PsrResponseInterface;
use Symfony\Component\HttpFoundation\Exception\BadRequestException;
use Symfony\Component\HttpFoundation\Response;

class IAMFactoryFacade implements IAMFactoryFacadeInterface
{
    public function __construct(
        private readonly ClientAdapter $clientAdapter,
    ) {
    }

    #[\Override]
    public function createResourceByAdmin(string $resourceType, string $id): self
    {
        return $this->createResource(
            $resourceType,
            $id,
            $this->clientAdapter->getServiceClient(),
        );
    }

    #[\Override]
    public function createResourceByConnectedUser(string $resourceType, string $id): self
    {
        return $this->createResource(
            $resourceType,
            $id,
            $this->clientAdapter->getClient(),
        );
    }

    private function createResource(string $resourceType, string $id, JaneClient $client): self
    {
        /** @var PsrResponseInterface $response */
        $response = $client->postResourceCollection(
            (new Resource())
                ->setSlug(self::BSM_RESOURCE_PREFIX.$resourceType.':'.$id)
                ->setResourceType('/api/resource_types/'.self::BSM_RESOURCE_PREFIX.$resourceType),
            NoahVetClient::FETCH_RESPONSE,
        );

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

        return $this;
    }
}
