<?php

declare(strict_types=1);

/** POST /api/v1/administration/migrations/apply */
final class MyronApplyPendingMigrationsAction implements MyronAction
{
    public function __construct(private readonly MyronMigrationOperationsService $service) {}

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri: '/api/v1/administration/migrations/apply',
            method: 'POST',
            domain: 'administration',
            resource: 'application-migrations',
            verb: 'apply-pending',
            inputSchema: ['type' => 'object', 'properties' => [], 'additionalProperties' => false],
            outputSchema: ['type' => 'object', 'properties' => []],
            requiredScope: MyronApiScopes::ADMINISTRATION_WRITE,
            summary: 'Apply all registered pending Core and trusted Module migrations through the canonical runner.',
            sideEffects: ['applies registered pending database migrations', 'reconciles completed trusted Module migration handoffs'],
            preconditions: ['Caller has administration.write and updates.security.', 'Only migrations registered by Core or recognized trusted Modules are eligible.'],
            postconditions: ['Applied versions are recorded in schema_migrations.', 'Failed migrations and Module handoffs remain pending.'],
            audienceClass: 4,
            snapshotInclude: false,
            exposeToMcp: true,
            requiredCapability: 'updates.security',
        );
    }

    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        try {
            return MyronActionResult::ok($this->service->applyPending());
        } catch (Throwable) {
            return MyronActionResult::error(
                'migration_apply_failed',
                'Pending migrations could not be applied. They remain pending; review the server log and retry.'
            );
        }
    }
}
