<?php

namespace NoahVet\Reef\Infrastructure\Security\IAM\Generator;

use NoahVet\Reef\Domain\Security\Model\Resource;
use NoahVet\Reef\Domain\Security\Model\ResourceGroupWithMembers;

/**
 * Delegates resource generation to a set of specialized generators.
 * Inject all InternalGeneratorInterface implementations to this service.
 */
class IAMResourceGenerator
{
    /**
     * @var iterable<InternalGeneratorInterface>
     */
    protected iterable $generators;

    /**
     * @param iterable<InternalGeneratorInterface> $generators
     */
    public function __construct(
        iterable $generators,
    ) {
        $this->generators = $generators;
    }

    /**
     * @return array<\NoahVet\Reef\Domain\Security\Model\Resource|ResourceGroupWithMembers>
     */
    public function generate(mixed $subject): array
    {
        $ret = [];

        foreach ($this->generators as $generator) {
            if (!$generator->canGenerate($subject)) {
                continue;
            }

            if ($generator instanceof InternalResourceGeneratorInterface) {
                $ret[] = $generator->generateResource($subject);
            }

            if ($generator instanceof InternalResourceGroupGeneratorInterface) {
                $ret[] = $generator->generateGroup($subject);
            }
        }

        return $ret;
    }
}
