<?php

declare(strict_types=1);

final class MyronListMailTransportsAction implements MyronAction
{
    public function __construct(private readonly MailTransportRegistry $registry)
    {
    }

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri: '/api/v1/administration/mail/transports',
            method: 'GET',
            domain: 'administration.mailTransports',
            resource: 'mail-transport',
            verb: 'list',
            inputSchema: ['type' => 'object', 'properties' => []],
            outputSchema: ['type' => 'object', 'properties' => ['transports' => ['type' => 'object']]],
            requiredScope: MyronApiScopes::ADMINISTRATION_READ,
            summary: 'List registered mail transport descriptors.',
            exposeToMcp: true,
        );
    }

    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        $entitlement = $this->requireCapability('mail.multiple_configs');
        if ($entitlement !== null) {
            return $entitlement;
        }
        return MyronActionResult::ok(['transports' => $this->registry->knownTransports()]);
    }

    private function requireCapability(string $capability): ?MyronActionResult
    {
        if (!function_exists('myronEntitlementGate')) {
            return null;
        }
        try {
            $decision = myronEntitlementGate()->evaluate($capability);
        } catch (Throwable) {
            return MyronActionResult::error('entitlement_denied', 'This feature is not available for the current license.');
        }
        return in_array((string) ($decision['outcome'] ?? ''), ['allowed', 'warn'], true)
            ? null
            : MyronActionResult::error('entitlement_denied', 'This feature is not available for the current license.');
    }
}
