<?php

declare(strict_types=1);

/**
 * APO-196 Card 6 — GET /api/v1/administration/updates/status
 *
 * APO-205 Card 1: exposeToMcp flipped from false → true. "Are updates available?"
 * is an operator-visible state read AI clients should be able to answer; the prior
 * operator-only framing conflated reads with the mutating apply/check/dismiss
 * actions. Architecture log full-parity-mcp-2026-05-10.md §3.
 */
final class MyronGetUpdateStatusAction implements MyronAction
{
    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri: '/api/v1/administration/updates/status', method: 'GET',
            domain: 'administration', resource: 'application-update-status', verb: 'get',
            inputSchema: ['type' => 'object', 'properties' => []],
            outputSchema: ['type' => 'object', 'properties' => []],
            requiredScope: MyronApiScopes::ADMINISTRATION_READ,
            summary: 'Get application update status — current installed version, available remote update (if any), and last-check timestamp. Read-only.',
            audienceClass: 3,
            snapshotInclude: false,
            exposeToMcp: true,
        );
    }
    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        $entitlement = $this->requireCapability('updates.security');
        if ($entitlement !== null) {
            return $entitlement;
        }
        $state = function_exists('myronRemoteUpdateStateRepository')
            ? (array) myronRemoteUpdateStateRepository()->get()
            : [];
        $settings = function_exists('myronRemoteUpdateSettingsRepository')
            ? (array) myronRemoteUpdateSettingsRepository()->get()
            : [];
        return MyronActionResult::ok([
            'state'    => $state,
            'settings' => $settings,
        ]);
    }

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