<?php

declare(strict_types=1);

/** POST /api/v1/administration/license-manager/install-package */
final class MyronInstallModulePackageAction implements MyronAction
{
    public function __construct(private readonly MyronModuleLicenseManagerService $service) {}

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri: '/api/v1/administration/license-manager/install-package',
            method: 'POST',
            domain: 'administration',
            resource: 'license-manager',
            verb: 'install-module-package',
            inputSchema: [
                'type' => 'object',
                'properties' => [
                    'skuId' => ['type' => 'string'],
                    'sku_id' => ['type' => 'string'],
                ],
                'required' => ['skuId'],
            ],
            outputSchema: [
                'type' => 'object',
                'properties' => [
                    'outcome' => ['type' => 'string'],
                    'moduleSlug' => ['type' => ['string', 'null']],
                    'operatorMessage' => ['type' => 'string'],
                    'packageHandoff' => ['type' => 'object'],
                ],
            ],
            requiredScope: MyronApiScopes::ADMINISTRATION_WRITE,
            summary: 'Install or upgrade a signed paid Module package for an already-active Module entitlement.',
            sideEffects: ['downloads and atomically applies a signed module package', 'appends sanitized module install or upgrade audit records'],
            audienceClass: 4,
            snapshotInclude: false,
            exposeToMcp: true,
        );
    }

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