<?php

declare(strict_types=1);

/**
 * APO-186 Card 3 — Worked-example MyronAction.
 *
 * URI:    PATCH /api/v1/design/footers/{variantId}/default
 * Scope:  design.write
 *
 * Equivalent to the existing admin form POST `action=set-default-footer-design`.
 * Both paths funnel through MyronFooterDesignActionService::setDefault, so
 * dual-mode equivalence is guaranteed by construction.
 */
final class MyronSetFooterDefaultAction implements MyronAction
{
    public function __construct(
        private readonly MyronFooterDesignActionService $service,
    ) {
    }

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri:           '/api/v1/design/footers/{variantId}/default',
            method:        'PATCH',
            domain:        'design',
            resource:      'footer',
            verb:          'set-default',
            inputSchema:   [
                'type'       => 'object',
                'properties' => [
                    'variantId' => ['type' => 'string'],
                ],
                'required'   => ['variantId'],
            ],
            outputSchema:  [
                'type'       => 'object',
                'properties' => [
                    'variantId'       => ['type' => 'string'],
                    'previousDefault' => ['type' => 'string'],
                ],
            ],
            requiredScope: MyronApiScopes::DESIGN_WRITE,
            summary:       'Set the global default footer variant. Templates with chrome.footer.inherit:"global" render the new default.',
            sideEffects:   ['writes footer_designs.is_default'],
            preconditions: [
                'variant exists in valid variants',
                'variant is_activated',
            ],
            postconditions: ['exactly one footer_designs row has is_default=1'],
            audienceClass:  4,
            adminAliases:   ['set-default-footer-design'],
        );
    }

    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        try {
            $result = $this->service->setDefault((string) ($input['variantId'] ?? ''), $caller);
            return MyronActionResult::ok($result);
        } 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());
        }
    }
}
