<?php

declare(strict_types=1);

/** APO-196 Card 6 — GET /api/v1/administration/mail (sanitised — no credentials) */
final class MyronGetMailConfigAction implements MyronAction
{
    public function __construct(private readonly MyronMailSettingsRepository $repo) {}
    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri: '/api/v1/administration/mail', method: 'GET',
            domain: 'administration', resource: 'mail-config', verb: 'get',
            inputSchema: ['type' => 'object', 'properties' => []],
            outputSchema: ['type' => 'object', 'properties' => []],
            requiredScope: MyronApiScopes::ADMINISTRATION_READ,
            summary: 'Get the mail configuration (host, port, encryption, from-address). Credential fields are redacted in the response.',
            audienceClass: 3,
            snapshotInclude: true, snapshotKey: 'administration.mailConfig',
            exposeToMcp: true,
        );
    }
    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        $entitlement = $this->requireCapability('mail.multiple_configs');
        if ($entitlement !== null) {
            return $entitlement;
        }
        $config = method_exists($this->repo, 'getSettings') ? (array) $this->repo->getSettings() : [];
        // Sanitise credential fields.
        foreach (['smtp_password', 'smtpPassword', 'api_key', 'apiKey', 'password'] as $key) {
            if (isset($config[$key]) && $config[$key] !== '' && $config[$key] !== null) {
                $config[$key] = '[REDACTED]';
            }
        }
        return MyronActionResult::ok($config);
    }

    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.');
    }
}
