<?php

declare(strict_types=1);

/**
 * APO-196 Card 2 — Save mail settings.
 *
 * URI:   PATCH /api/v1/administration/mail
 * Scope: administration.write  · exposeToMcp:TRUE (APO-205-007 substrate correction).
 * Input-direction credential; the paired GET returns sanitised data and is
 * already exposed. An MCP agent granted administration.write inherits the
 * operator's mail-config-rotation capability.
 */
final class MyronSaveMailSettingsAction implements MyronAction
{
    public function __construct(private readonly MyronMailActionService $service) {}

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri: '/api/v1/administration/mail', method: 'PATCH',
            domain: 'administration', resource: 'mail-settings', verb: 'save',
            inputSchema: ['type' => 'object', 'properties' => []],
            outputSchema: ['type' => 'object', 'properties' => ['saved' => ['type' => 'boolean']]],
            requiredScope: MyronApiScopes::ADMINISTRATION_WRITE,
            summary: 'Save mail (SMTP/ESP) configuration including provider, host, port, encryption mode, from-address, and credentials. Input-direction only — the GET endpoint returns sanitised data.',
            sideEffects: ['updates mail_settings row'],
            preconditions: [], postconditions: ['mail config persisted'],
            audienceClass: 4, adminAliases: ['save-mail-settings'],
            snapshotInclude: false, exposeToMcp: true,
        );
    }

    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        $entitlement = $this->requireCapability('mail.multiple_configs');
        if ($entitlement !== null) {
            return $entitlement;
        }
        try {
            return MyronActionResult::ok($this->service->saveSettings($input, $caller));
        } catch (Throwable $e) { return MyronActionResult::error('business_rule_failed', $e->getMessage()); }
    }

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