<?php

declare(strict_types=1);

/**
 * APO-193 Card 4 — Apply default zone content for the active site type's bundle.
 *
 * URI:   POST /api/v1/design/footers/{variantId}/zones/{zoneId}/apply-defaults
 * Scope: design.write
 */
final class MyronApplyFooterZoneDefaultsAction implements MyronAction
{
    public function __construct(
        private readonly MyronFooterDesignActionService $service,
    ) {
    }

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri:           '/api/v1/design/footers/{variantId}/zones/{zoneId}/apply-defaults',
            method:        'POST',
            domain:        'design',
            resource:      'footer-zone',
            verb:          'apply-defaults',
            inputSchema:   [
                'type'       => 'object',
                'properties' => [
                    'variantId' => ['type' => 'string'],
                    'zoneId'    => ['type' => 'string'],
                ],
                'required'   => ['variantId', 'zoneId'],
            ],
            outputSchema:  [
                'type'       => 'object',
                'properties' => [
                    'variantId' => ['type' => 'string'],
                    'zoneId'    => ['type' => 'string'],
                    'applied'   => ['type' => 'boolean'],
                ],
            ],
            requiredScope:   MyronApiScopes::DESIGN_WRITE,
            summary:         'Apply the active site type bundle\'s default content to a specific footer zone — seeds the zone with curated copy.',
            sideEffects:     ['writes footer_designs.zone_content[zoneId]'],
            preconditions:   ['variant exists in valid variants', 'site type bundle has defaults for this zone'],
            postconditions:  ['zone content populated with defaults when applied=true; unchanged when applied=false'],
            audienceClass:   4,
            adminAliases:    ['apply-defaults-for-zone'],
            snapshotInclude: false,
            exposeToMcp:     true,
        );
    }

    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        try {
            return MyronActionResult::ok($this->service->applyDefaultsForZone(
                (string) ($input['variantId'] ?? ''),
                (string) ($input['zoneId'] ?? ''),
                $caller
            ));
        } catch (MyronActionPreconditionError $e) {
            return MyronActionResult::error('precondition_failed', $e->getMessage());
        } catch (InvalidArgumentException $e) {
            return MyronActionResult::error('input_invalid', $e->getMessage());
        } catch (Throwable $e) {
            return MyronActionResult::error('business_rule_failed', $e->getMessage());
        }
    }
}
