<?php

declare(strict_types=1);

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

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri: '/api/v1/content/pages/{pageId}/author',
            method: 'PATCH',
            domain: 'content',
            resource: 'page-author',
            verb: 'set',
            inputSchema: [
                'type' => 'object',
                'properties' => [
                    'pageId' => ['type' => 'string'],
                    'authorName' => ['type' => 'string'],
                    'authorUserId' => ['type' => 'string'],
                    'avatarFileId' => ['type' => 'string'],
                    'bio' => ['type' => 'string'],
                    'author' => ['type' => 'object'],
                ],
                'required' => ['pageId'],
            ],
            outputSchema: ['type' => 'object', 'properties' => ['pageId' => ['type' => 'string'], 'author' => ['type' => 'object']]],
            requiredScope: MyronApiScopes::CONTENT_WRITE,
            summary: 'Set author metadata for a page or blog post without changing unrelated page content.',
            sideEffects: ['inserts new page_versions row'],
            preconditions: ['page exists'],
            postconditions: ['author metadata is stored in the page content envelope'],
            audienceClass: 4,
            snapshotInclude: false,
            exposeToMcp: true,
        );
    }

    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        try {
            $author = is_array($input['author'] ?? null) ? (array) $input['author'] : [];
            foreach (['authorName', 'authorUserId', 'avatarFileId', 'bio'] as $field) {
                if (array_key_exists($field, $input)) {
                    $author[$field] = $input[$field];
                }
            }
            return MyronActionResult::ok($this->service->setAuthor((string) ($input['pageId'] ?? ''), $author, $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());
        }
    }
}
