<?php

declare(strict_types=1);

final class MyronSaveSeoSettingsAction implements MyronAction
{
    public function __construct(private readonly MyronSiteSettingsActionService $service)
    {
    }

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri: '/api/v1/administration/seo-settings',
            method: 'POST',
            domain: 'administration',
            resource: 'seo-settings',
            verb: 'save',
            inputSchema: ['type' => 'object', 'properties' => ['settings' => ['type' => 'object']], 'required' => ['settings']],
            outputSchema: ['type' => 'object', 'properties' => ['updated' => ['type' => 'boolean']]],
            requiredScope: MyronApiScopes::ADMINISTRATION_WRITE,
            summary: 'Save site-level SEO settings, schema defaults, social metadata defaults, and output toggles.',
            sideEffects: ['updates site_settings SEO columns', 'refreshes settings cache'],
            preconditions: ['caller holds administration.write'],
            postconditions: ['SEO settings persisted'],
            audienceClass: 4,
            adminAliases: ['save-seo-settings'],
            snapshotInclude: false,
            exposeToMcp: true,
        );
    }

    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        try {
            $settings = is_array($input['settings'] ?? null) ? (array) $input['settings'] : [];
            if (function_exists('myronSiteSettings')) {
                $settings = array_merge(myronSiteSettings(), $settings);
            }
            return MyronActionResult::ok($this->service->saveSettings($settings, null, $caller));
        } catch (InvalidArgumentException $e) {
            return MyronActionResult::error('input_invalid', $e->getMessage());
        } catch (Throwable $e) {
            return MyronActionResult::error('business_rule_failed', $e->getMessage());
        }
    }
}
