<?php

declare(strict_types=1);

/**
 * APO-194 Card 5 — Assign navigation + footer chrome to a template.
 *
 * URI:   POST /api/v1/design/templates/{templateId}/chrome
 * Scope: design.write
 */
final class MyronAssignTemplateChromeAction implements MyronAction
{
    public function __construct(
        private readonly MyronTemplateChromeActionService $service,
    ) {
    }

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri:           '/api/v1/design/templates/{templateId}/chrome',
            method:        'POST',
            domain:        'design',
            resource:      'template-chrome',
            verb:          'assign',
            inputSchema:   [
                'type'       => 'object',
                'properties' => [
                    'templateId'         => ['type' => 'string'],
                    'navigationDesignId' => ['type' => 'string'],
                    'footerVariantId'    => ['type' => 'string'],
                ],
                'required'   => ['templateId'],
            ],
            outputSchema:  [
                'type'       => 'object',
                'properties' => [
                    'templateId'         => ['type' => 'string'],
                    'navigationDesignId' => ['type' => 'string'],
                    'footerVariantId'    => ['type' => 'string'],
                ],
            ],
            requiredScope:   MyronApiScopes::DESIGN_WRITE,
            summary:         'Assign navigation version + footer variant to a template. footerVariantId may be empty (or "inherit") to fall back to the global default footer.',
            sideEffects:     ['writes template_chrome_assignments row'],
            preconditions:   ['template exists; navigationDesignId references existing version or empty for default; footer variant exists or is "inherit"'],
            postconditions:  ['template_chrome_assignments reflects input'],
            audienceClass:   4,
            adminAliases:    ['update-template-chrome-assignment'],
            snapshotInclude: false,
            exposeToMcp:     true,
        );
    }

    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        try {
            $footer = (string) ($input['footerVariantId'] ?? '');
            $footerForRepo = in_array($footer, ['', 'inherit_site', 'inherit_seed', 'inherit'], true) ? null : $footer;
            return MyronActionResult::ok($this->service->assign(
                (string) ($input['templateId'] ?? ''),
                (string) ($input['navigationDesignId'] ?? ''),
                $footerForRepo,
                $caller
            ));
        } catch (InvalidArgumentException $e) {
            return MyronActionResult::error('input_invalid', $e->getMessage());
        } catch (Throwable $e) {
            return MyronActionResult::error('business_rule_failed', $e->getMessage());
        }
    }
}
