<?php

namespace NoahVet\Reef\Infrastructure\Security\Api;

use NoahVet\Reef\Domain\Security\Port\PolicyResultStoreInterface;
use NoahVet\Reef\Iam\Client;
use NoahVet\Reef\Iam\Model\PolicyResult;

class JanePolicyResultStore implements PolicyResultStoreInterface
{
    public function __construct(
        protected readonly Client $iamServiceClient,
    ) {
    }

    #[\Override]
    public function findEtag(string $policyName, string $subjectIdentifier): ?string
    {
        /** @var PolicyResult[] $results */
        $results = $this->iamServiceClient->getPolicyResultCollection(
            [
                'name' => $policyName,
                'subject' => $subjectIdentifier,
            ],
        );

        if (1 === \count($results)) {
            return $results[0]->getEtag();
        }

        return null;
    }

    #[\Override]
    public function findEtags(string $policyName, array $subjectIdentifiers): array
    {
        $ret = [];

        for ($page = 1; true; ++$page) {
            /** @var PolicyResult[] $policyResults */
            $policyResults = $this->iamServiceClient->getPolicyResultCollection(
                [
                    'name' => $policyName,
                    'subject[]' => $subjectIdentifiers,
                    'page' => $page,
                ],
            );

            if (empty($policyResults)) {
                break;
            }

            $ret = \array_reduce(
                $policyResults,
                static function (array $carry, PolicyResult $policyResultGet): array {
                    $carry[$policyResultGet->getSubject()] = $policyResultGet->getEtag();

                    return $carry;
                },
                $ret,
            );
        }

        return $ret;
    }
}
