<?php

declare(strict_types=1);

final class MyronSavePageSeoAction implements MyronAction
{
    public function __construct(private readonly MyronPagesActionService $service)
    {
    }

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri: '/api/v1/content/pages/{pageId}/seo',
            method: 'POST',
            domain: 'content',
            resource: 'page-seo',
            verb: 'save',
            inputSchema: [
                'type' => 'object',
                'properties' => [
                    'pageId' => ['type' => 'string'],
                    'seo' => ['type' => 'object'],
                ],
                'required' => ['pageId', 'seo'],
            ],
            outputSchema: ['type' => 'object', 'properties' => ['pageId' => ['type' => 'string'], 'updated' => ['type' => 'boolean']]],
            requiredScope: MyronApiScopes::CONTENT_WRITE,
            summary: 'Save per-page SEO overrides without publishing the page.',
            sideEffects: ['inserts a new page_versions draft row with SEO override fields'],
            preconditions: ['page exists'],
            postconditions: ['draft SEO override fields persisted'],
            audienceClass: 4,
            adminAliases: ['save-page-seo'],
            snapshotInclude: false,
            exposeToMcp: true,
        );
    }

    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        try {
            return MyronActionResult::ok($this->service->saveSeo(
                (string) ($input['pageId'] ?? ''),
                is_array($input['seo'] ?? null) ? (array) $input['seo'] : [],
                $caller
            ));
        } catch (MyronActionPreconditionError $e) {
            return MyronActionResult::error('precondition_failed', $e->getMessage());
        } catch (InvalidArgumentException $e) {
            return MyronActionResult::error('input_invalid', $e->getMessage());
        } catch (Throwable $e) {
            return MyronActionResult::error('business_rule_failed', $e->getMessage());
        }
    }
}
