<?php

declare(strict_types=1);

/**
 * APO-195 Card 1 — Publish a page.
 *
 * URI:   POST /api/v1/content/pages/{pageId}/publish
 * Scope: content.write
 */
final class MyronPublishPageAction implements MyronAction
{
    public function __construct(private readonly MyronPagesActionService $service) {}

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri: '/api/v1/content/pages/{pageId}/publish', method: 'POST',
            domain: 'content', resource: 'page', verb: 'publish',
            inputSchema: [
                'type' => 'object',
                'properties' => [
                    'pageId'      => ['type' => 'string'],
                    'publishedAt' => ['type' => 'string'],
                ],
                'required' => ['pageId'],
            ],
            outputSchema: ['type' => 'object', 'properties' => ['pageId' => ['type' => 'string'], 'publishedAt' => ['type' => 'string']]],
            requiredScope: MyronApiScopes::CONTENT_WRITE,
            summary: 'Publish the current draft state of a page; optional publishedAt overrides the timestamp.',
            sideEffects: ['updates pages.publication_state to published; sets current_published_version_id'],
            preconditions: ['page exists'],
            postconditions: ['page is published and visible at its path'],
            audienceClass: 4,
            adminAliases: ['publish-page'],
            snapshotInclude: false,
            exposeToMcp: true,
        );
    }

    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        try {
            return MyronActionResult::ok($this->service->publish(
                (string) ($input['pageId'] ?? ''),
                isset($input['publishedAt']) ? (string) $input['publishedAt'] : null,
                $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());
        }
    }
}
