<?php

declare(strict_types=1);

/** APO-196 Card 5 — PATCH /api/v1/administration/users/registration-settings */
final class MyronSaveRegistrationSettingsAction implements MyronAction
{
    public function __construct(private readonly MyronIdentityActionService $service) {}
    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri: '/api/v1/administration/users/registration-settings', method: 'PATCH',
            domain: 'administration', resource: 'registration-settings', verb: 'save',
            inputSchema: [
                'type' => 'object',
                'properties' => ['allowedDomains' => ['type' => 'array']],
                'required' => ['allowedDomains'],
            ],
            outputSchema: ['type' => 'object', 'properties' => []],
            requiredScope: MyronApiScopes::ADMINISTRATION_WRITE,
            summary: 'Save registration settings (allowed email-domain allow-list for new sign-ups).',
            sideEffects: ['updates registration_settings row'],
            preconditions: ['caller is administrator'],
            postconditions: ['allowed-domains list reflects input'],
            audienceClass: 4, adminAliases: ['save-registration-settings'],
            snapshotInclude: false, exposeToMcp: false,
        );
    }
    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        try {
            $domains = is_array($input['allowedDomains'] ?? null) ? array_map('strval', (array) $input['allowedDomains']) : [];
            return MyronActionResult::ok($this->service->saveRegistrationSettings($domains, $caller));
        } catch (Throwable $e) { return MyronActionResult::error('business_rule_failed', $e->getMessage()); }
    }
}
