<?php

declare(strict_types=1);

/** POST /api/v1/design/creative-library/buttons/activate */
final class MyronActivateCreativeLibraryButtonStyleAction 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/buttons/activate', method: 'POST',
            domain: 'design', resource: 'creative_library', verb: 'activate-button',
            inputSchema: ['type' => 'object', 'properties' => ['button_style' => ['type' => 'string']], 'required' => ['button_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 button creative.',
            sideEffects: ['updates site_settings.creative_button_style'], audienceClass: 4,
            adminAliases: ['activate-button-style'], snapshotInclude: false, exposeToMcp: true,
        );
    }

    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        try {
            $buttonStyle = myronNormalizeSlug((string) ($input['button_style'] ?? ''));
            $entry = $buttonStyle !== '' ? $this->catalog->find($buttonStyle) : null;
            if (!is_array($entry) || (string) ($entry['category'] ?? '') !== 'button' || (string) ($entry['tier'] ?? '') !== 'site') {
                return MyronActionResult::error('input_invalid', 'Choose a supported site button creative.');
            }
            $current = $this->settings->creativeSettings();
            return MyronActionResult::ok($this->settings->saveCreativeSettings($current['navStyle'] ?? null, $buttonStyle, $current['navParams'] ?? []));
        } catch (Throwable $e) {
            return MyronActionResult::error('business_rule_failed', $e->getMessage());
        }
    }
}
