<?php

declare(strict_types=1);

final class MyronBundleDisableAction implements MyronAction
{
    public function __construct(private readonly MyronBundleDisableService $service) {}

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri: '/api/v1/administration/bundles/{bundleId}/disable',
            method: 'POST',
            domain: 'administration',
            resource: 'bundle',
            verb: 'disable',
            inputSchema: [
                'type' => 'object',
                'properties' => [
                    'bundleId' => ['type' => 'string'],
                    'redirect_map' => ['type' => 'object'],
                ],
                'required' => ['bundleId'],
            ],
            outputSchema: ['type' => 'object', 'properties' => ['audit_id' => ['type' => 'string'], 'summary' => ['type' => 'object']]],
            requiredScope: MyronApiScopes::ADMINISTRATION_WRITE,
            summary: 'Disable a non-primary site type bundle with impact audit, soft-disabled pages, menu cleanup, and 302 redirects.',
            sideEffects: ['updates pages.disabled_by_bundle_removal_at', 'deletes menu_items for disabled pages', 'writes disabled_page_redirects', 'updates bundle_activation_state', 'writes bundle_activation_audit'],
            preconditions: ['bundle exists', 'bundle is non-primary', 'bundle is enabled', 'redirect fallbacks are safe'],
            postconditions: ['bundle disabled atomically'],
            audienceClass: 4,
            adminAliases: ['bundles.disable', 'disable-site-type-bundle'],
            snapshotInclude: false,
            exposeToMcp: true,
        );
    }

    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        try {
            return MyronActionResult::ok($this->service->disable(
                (string) ($input['bundleId'] ?? ''),
                is_array($input['redirect_map'] ?? null) ? $input['redirect_map'] : [],
                $caller
            ));
        } catch (InvalidArgumentException $e) {
            $message = $e->getMessage();
            return MyronActionResult::error($message === 'Bundle not found.' ? 'not_found' : 'input_invalid', $message);
        } catch (DomainException $e) {
            return MyronActionResult::error('precondition_failed', $e->getMessage());
        } catch (RuntimeException $e) {
            return MyronActionResult::error('conflict', $e->getMessage());
        } catch (Throwable $e) {
            return MyronActionResult::error('business_rule_failed', $e->getMessage());
        }
    }
}
