<?php

declare(strict_types=1);

/** POST /api/v1/administration/license/refresh */
final class MyronRefreshLicenseAction implements MyronAction
{
    public function __construct(private readonly MyronLicenseActivationService $service) {}

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri: '/api/v1/administration/license/refresh', method: 'POST',
            domain: 'administration', resource: 'license', verb: 'refresh',
            inputSchema: [
                'type' => 'object',
                'properties' => [
                    'license_key' => ['type' => 'string'],
                    'deployment_key' => ['type' => 'string'],
                    'license_plan' => ['type' => 'string'],
                    'license_environment' => ['type' => 'string'],
                    'siteUrl' => ['type' => 'string'],
                    'confirm_downgrade_backup' => ['type' => 'boolean'],
                ],
                'required' => ['license_key', 'license_plan', 'license_environment'],
            ],
            outputSchema: ['type' => 'object', 'properties' => ['plan' => ['type' => 'string'], 'status' => ['type' => 'string']]],
            requiredScope: MyronApiScopes::ADMINISTRATION_WRITE,
            summary: 'Refresh the local license entitlement snapshot from the license service.',
            sideEffects: ['updates license activation state', 'appends license audit records'], audienceClass: 4,
            adminAliases: ['refresh-license'], snapshotInclude: false, exposeToMcp: false,
        );
    }

    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        try {
            $siteUrl = trim((string) ($input['siteUrl'] ?? '')) ?: myronAppUrl();
            $snapshot = $this->service->refreshFromInput($input, $siteUrl, $caller->callerId);
            return MyronActionResult::ok($snapshot->toArray());
        } catch (InvalidArgumentException $e) {
            return MyronActionResult::error('input_invalid', $e->getMessage());
        } catch (Throwable $e) {
            return MyronActionResult::error('business_rule_failed', $e->getMessage());
        }
    }
}
