<?php

namespace NoahVet\Reef\Infrastructure\Security\Api;

use NoahVet\Reef\Domain\Security\Policy\PolicyResult;
use NoahVet\Reef\Domain\Security\Port\PolicyResultPublisherInterface;
use NoahVet\Reef\Exception\IAMException;
use NoahVet\Reef\Iam\Client;
use NoahVet\Reef\Iam\Endpoint\PostPolicyResultCollection;
use NoahVet\Reef\Infrastructure\Security\IAM\Transformer\PolicyResultTransformerInterface;

class JanePolicyResultPublisher implements PolicyResultPublisherInterface
{
    public function __construct(
        private readonly Client $iamServiceClient,
        private readonly PolicyResultTransformerInterface $transformer,
    ) {
    }

    #[\Override]
    public function publish(PolicyResult $result): void
    {
        $response = $this->iamServiceClient->executeRawEndpoint(
            new PostPolicyResultCollection(
                $this->transformer->toApiDto($result),
            ),
        );

        if (200 > $response->getStatusCode() || 300 <= $response->getStatusCode()) {
            throw new IAMException(
                'Result from IAM not parsable : '.$response->getBody()->getContents(),
                $response->getStatusCode(),
            );
        }
    }
}
