<?php

declare(strict_types=1);

/** APO-196 Card 3 — PATCH /api/v1/administration/updates/manifest-url (exposeToMcp:true, APO-205-007). */
final class MyronSaveRemoteUpdateManifestUrlAction implements MyronAction
{
    public function __construct(private readonly MyronSiteSetupActionService $service) {}
    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri: '/api/v1/administration/updates/manifest-url', method: 'PATCH',
            domain: 'administration', resource: 'application-update', verb: 'save-manifest-url',
            inputSchema: [
                'type' => 'object',
                'properties' => ['manifestUrl' => ['type' => 'string']],
                'required' => ['manifestUrl'],
            ],
            outputSchema: ['type' => 'object', 'properties' => ['manifestUrl' => ['type' => 'string']]],
            requiredScope: MyronApiScopes::ADMINISTRATION_WRITE,
            summary: 'Save the remote update manifest URL (must be HTTPS).',
            sideEffects: ['updates remote_update_settings row'],
            preconditions: ['caller is administrator', 'URL is valid HTTPS'],
            postconditions: ['manifest URL persisted'],
            audienceClass: 4, adminAliases: ['save-remote-update-manifest-url'],
            snapshotInclude: false, exposeToMcp: true,
        );
    }
    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        try { return MyronActionResult::ok($this->service->saveRemoteUpdateManifestUrl((string) ($input['manifestUrl'] ?? ''), $caller)); }
        catch (MyronActionPreconditionError $e) { return MyronActionResult::error('precondition_failed', $e->getMessage()); }
        catch (InvalidArgumentException $e) { return MyronActionResult::error('input_invalid', $e->getMessage()); }
        catch (Throwable $e) { return MyronActionResult::error('business_rule_failed', $e->getMessage()); }
    }
}
