<?php

declare(strict_types=1);

final class MyronBundleEnableAction implements MyronAction
{
    public function __construct(private readonly MyronBundleEnableService $service) {}

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri: '/api/v1/administration/bundles/{bundleId}/enable',
            method: 'POST',
            domain: 'administration',
            resource: 'bundle',
            verb: 'enable',
            inputSchema: [
                'type' => 'object',
                'properties' => [
                    'bundleId' => ['type' => 'string'],
                    'conflict_resolution' => ['type' => 'string'],
                ],
                'required' => ['bundleId'],
            ],
            outputSchema: ['type' => 'object', 'properties' => ['audit_id' => ['type' => 'string'], 'summary' => ['type' => 'object']]],
            requiredScope: MyronApiScopes::ADMINISTRATION_WRITE,
            summary: 'Re-enable a disabled site type bundle, restoring pages/menu items and removing disable redirects.',
            sideEffects: ['updates pages.disabled_by_bundle_removal_at', 'restores menu_items', 'deletes disabled_page_redirects', 'updates bundle_activation_state', 'writes bundle_activation_audit'],
            preconditions: ['bundle exists', 'bundle is disabled'],
            postconditions: ['bundle enabled atomically or conflict payload returned'],
            audienceClass: 4,
            adminAliases: ['bundles.enable', 'enable-site-type-bundle'],
            snapshotInclude: false,
            exposeToMcp: true,
        );
    }

    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        try {
            $result = $this->service->enable(
                (string) ($input['bundleId'] ?? ''),
                (string) ($input['conflict_resolution'] ?? 'skip'),
                $caller
            );
            if (($result['conflict'] ?? false) === true) {
                return MyronActionResult::error('conflict', 'Re-enable would collide with currently published pages.');
            }
            return MyronActionResult::ok($result);
        } catch (InvalidArgumentException $e) {
            return MyronActionResult::error('not_found', $e->getMessage());
        } catch (RuntimeException $e) {
            return MyronActionResult::error('conflict', $e->getMessage());
        } catch (Throwable $e) {
            return MyronActionResult::error('business_rule_failed', $e->getMessage());
        }
    }
}
