<?php

declare(strict_types=1);

namespace NoahVet\Reef\Security\IAM;

use NoahVet\Reef\Jane\Client;
use NoahVet\Reef\Jane\Exception\BadRequestException;
use NoahVet\Reef\Security\IAM\Model\Resource;
use NoahVet\Reef\Security\IAM\Model\ResourceGroupWithMembers;
use Symfony\Component\HttpFoundation\Response;

class ResourceManager
{
    protected Client $client;

    public function __construct(
        Client $client,
    ) {
        $this->client = $client;
    }

    /**
     * Create the resource if needed in the IAM.
     */
    public function registerResource(Resource $resource): self
    {
        $response = $this->client->executeRawEndpoint(
            new \NoahVet\Reef\Jane\Endpoint\PostResourceCollection(
                (new \NoahVet\Reef\Jane\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(),
                ),
            );
        }

        return $this;
    }

    public function register(Resource|ResourceGroupWithMembers $resource): self
    {
        if ($resource instanceof Resource) {
            return $this->registerResource($resource);
        }

        // @todo Add ResourceGroupWithMembers management

        return $this;
    }
}
