<?php

declare(strict_types=1);

/** POST /api/v1/design/creative-library/navigation/activate */
final class MyronActivateCreativeLibraryNavStyleAction implements MyronAction
{
    public function __construct(
        private readonly MyronSiteSettingsRepository $settings,
        private readonly MyronCreativeLibraryCatalog $catalog,
    ) {}

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri: '/api/v1/design/creative-library/navigation/activate', method: 'POST',
            domain: 'design', resource: 'creative_library', verb: 'activate-navigation',
            inputSchema: [
                'type' => 'object',
                'properties' => [
                    'nav_style' => ['type' => 'string'],
                    'nav_params' => [
                        'type' => 'object',
                        'properties' => ['navRadius' => ['type' => 'string', 'enum' => ['pill', 'lg', 'md', 'sm', 'none']]],
                        'additionalProperties' => false,
                    ],
                ],
                'required' => ['nav_style'],
            ],
            outputSchema: ['type' => 'object', 'properties' => ['navStyle' => ['type' => ['string', 'null']], 'navParams' => ['type' => 'object'], 'btnStyle' => ['type' => ['string', 'null']]]],
            requiredScope: MyronApiScopes::DESIGN_WRITE,
            summary: 'Activate a site-level navigation creative.',
            sideEffects: ['updates site_settings.creative_nav_style', 'updates site_settings.creative_nav_params_json'], audienceClass: 4,
            adminAliases: ['activate-nav-style'], snapshotInclude: false, exposeToMcp: true,
        );
    }

    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        try {
            $navStyle = myronNormalizeSlug((string) ($input['nav_style'] ?? ''));
            $entry = $navStyle !== '' ? $this->catalog->find($navStyle) : null;
            if (!is_array($entry) || (string) ($entry['category'] ?? '') !== 'navigation' || (string) ($entry['tier'] ?? '') !== 'site') {
                return MyronActionResult::error('input_invalid', 'Choose a supported site navigation creative.');
            }
            $providedParams = $input['nav_params'] ?? [];
            if (!is_array($providedParams)) {
                return MyronActionResult::error('input_invalid', 'Navigation parameters must be an object.');
            }
            $supportedParams = array_values(array_filter(is_array($entry['supportedParams'] ?? null) ? $entry['supportedParams'] : [], 'is_array'));
            $supportedKeys = array_values(array_map(static fn (array $param): string => (string) ($param['key'] ?? ''), $supportedParams));
            foreach (array_keys($providedParams) as $key) {
                if (!in_array((string) $key, $supportedKeys, true)) {
                    return MyronActionResult::error('input_invalid', 'Choose supported navigation parameters.');
                }
            }
            $navParams = [];
            foreach ($supportedParams as $param) {
                $key = (string) ($param['key'] ?? '');
                if ($key !== 'navRadius') {
                    continue;
                }
                $value = myronNormalizeSlug((string) ($providedParams[$key] ?? ($param['default'] ?? 'pill')));
                $options = array_values(array_map('strval', is_array($param['options'] ?? null) ? $param['options'] : []));
                if (!in_array($value, $options, true)) {
                    return MyronActionResult::error('input_invalid', 'Choose a supported navigation radius.');
                }
                $navParams[$key] = $value;
            }
            $current = $this->settings->creativeSettings();
            return MyronActionResult::ok($this->settings->saveCreativeSettings($navStyle, $current['btnStyle'] ?? null, $navParams));
        } catch (Throwable $e) {
            return MyronActionResult::error('business_rule_failed', $e->getMessage());
        }
    }
}
