<?php

declare(strict_types=1);

/** APO-196 Card 3 — POST /api/v1/administration/updates/check-remote (exposeToMcp:true, APO-205-007). */
final class MyronCheckRemoteApplicationUpdateAction implements MyronAction
{
    public function __construct(private readonly MyronSiteSetupActionService $service) {}
    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri: '/api/v1/administration/updates/check-remote', method: 'POST',
            domain: 'administration', resource: 'application-update', verb: 'check-remote',
            inputSchema: ['type' => 'object', 'properties' => []],
            outputSchema: ['type' => 'object', 'properties' => []],
            requiredScope: MyronApiScopes::ADMINISTRATION_WRITE,
            summary: 'Check the remote update manifest for available updates; refreshes the local update-state cache and last-check timestamp.',
            sideEffects: ['fetches remote manifest; may update local update-state cache'],
            preconditions: ['caller is administrator'],
            postconditions: ['check result returned'],
            audienceClass: 4, adminAliases: ['check-remote-application-update'],
            snapshotInclude: false, exposeToMcp: true,
        );
    }
    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        $entitlement = $this->requireCapability('updates.security');
        if ($entitlement !== null) {
            return $entitlement;
        }
        try { return MyronActionResult::ok($this->service->checkRemoteApplicationUpdate($caller)); }
        catch (MyronActionPreconditionError $e) { return MyronActionResult::error('precondition_failed', $e->getMessage()); }
        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.');
    }
}
