<?php

declare(strict_types=1);

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

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri: '/api/v1/administration/license-manager/redeem',
            method: 'POST',
            domain: 'administration',
            resource: 'license-manager',
            verb: 'redeem-key',
            inputSchema: [
                'type' => 'object',
                'properties' => [
                    'licenseKey' => ['type' => 'string'],
                    'license_key' => ['type' => 'string'],
                    'activationToken' => ['type' => 'string'],
                    'activation_token' => ['type' => 'string'],
                    'skuId' => ['type' => 'string'],
                    'sku_id' => ['type' => 'string'],
                ],
                'required' => ['licenseKey'],
            ],
            outputSchema: [
                'type' => 'object',
                'properties' => [
                    'outcome' => ['type' => 'string'],
                    'moduleSlug' => ['type' => ['string', 'null']],
                    'auditEventId' => ['type' => 'string'],
                    'operatorMessage' => ['type' => 'string'],
                ],
            ],
            requiredScope: MyronApiScopes::ADMINISTRATION_WRITE,
            summary: 'Redeem a paid Module license key through the Stage A License Manager scaffold.',
            sideEffects: ['appends sanitized module redemption audit records'],
            audienceClass: 4,
            adminAliases: ['redeem-key', 'redeem-marketplace-token'],
            snapshotInclude: false,
            exposeToMcp: true,
        );
    }

    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        try {
            $licenseKey = (string) ($input['licenseKey'] ?? $input['license_key'] ?? '');
            $activationToken = (string) ($input['activationToken'] ?? $input['activation_token'] ?? '');
            $skuId = (string) ($input['skuId'] ?? $input['sku_id'] ?? 'pro-funnels');
            if (trim($activationToken) !== '') {
                return MyronActionResult::ok($this->service->redeemActivationToken($activationToken, $caller->callerId));
            }
            return MyronActionResult::ok($this->service->redeemKey($licenseKey, $caller->callerId, $skuId));
        } catch (InvalidArgumentException $e) {
            return MyronActionResult::error('input_invalid', $e->getMessage());
        } catch (Throwable $e) {
            return MyronActionResult::error('business_rule_failed', $e->getMessage());
        }
    }
}
