<?php

declare(strict_types=1);

/**
 * APO-193 Card 4 — Apply a site-type-bundle footer recommendation.
 *
 * URI:   POST /api/v1/design/footers/recommendations/apply
 * Scope: design.write
 */
final class MyronApplyFooterRecommendationAction implements MyronAction
{
    public function __construct(
        private readonly MyronFooterDesignActionService $service,
    ) {
    }

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri:           '/api/v1/design/footers/recommendations/apply',
            method:        'POST',
            domain:        'design',
            resource:      'footer-recommendation',
            verb:          'apply',
            inputSchema:   [
                'type'       => 'object',
                'properties' => [
                    'bundleId'  => ['type' => 'string'],
                    'variantId' => ['type' => 'string'],
                ],
                'required'   => ['bundleId', 'variantId'],
            ],
            outputSchema:  [
                'type'       => 'object',
                'properties' => [
                    'bundleId'  => ['type' => 'string'],
                    'variantId' => ['type' => 'string'],
                ],
            ],
            requiredScope:   MyronApiScopes::DESIGN_WRITE,
            summary:         'Apply a footer recommendation for the active site type bundle — sets the recommended variant as the new default.',
            sideEffects:     ['writes footer_designs.is_default', 'writes recommendation state'],
            preconditions:   ['bundle exists', 'variant exists in valid variants'],
            postconditions:  ['recommendation marked applied'],
            audienceClass:   4,
            adminAliases:    ['apply-footer-recommendation'],
            snapshotInclude: false,
            exposeToMcp:     true,
        );
    }

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