<?php

declare(strict_types=1);

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

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri: '/api/v1/administration/license/remove', method: 'POST',
            domain: 'administration', resource: 'license', verb: 'remove',
            inputSchema: [
                'type' => 'object',
                'properties' => [
                    'confirm_remove_license_phrase' => ['type' => 'string'],
                    'siteUrl' => ['type' => 'string'],
                ],
                'required' => ['confirm_remove_license_phrase'],
            ],
            outputSchema: ['type' => 'object', 'properties' => ['removed' => ['type' => 'boolean']]],
            requiredScope: MyronApiScopes::ADMINISTRATION_DESTRUCTIVE,
            summary: 'Remove the current license activation from this site after catastrophic confirmation.',
            sideEffects: ['deactivates remote license activation', 'clears local license state', 'appends license audit records'],
            audienceClass: 4,
            adminAliases: ['remove-license'], snapshotInclude: false, exposeToMcp: false,
        );
    }

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