<?php

declare(strict_types=1);

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

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri: '/api/v1/content/pages/{pageId}/unpublish', method: 'POST',
            domain: 'content', resource: 'page', verb: 'unpublish',
            inputSchema: ['type' => 'object', 'properties' => ['pageId' => ['type' => 'string']], 'required' => ['pageId']],
            outputSchema: ['type' => 'object', 'properties' => ['pageId' => ['type' => 'string']]],
            requiredScope: MyronApiScopes::CONTENT_WRITE,
            summary: 'Unpublish a page (revert to draft state; preserves draft content).',
            sideEffects: ['updates pages.publication_state to draft'],
            preconditions: ['page exists'],
            postconditions: ['page no longer visible at its public path'],
            audienceClass: 4,
            adminAliases: [],
            snapshotInclude: false,
            exposeToMcp: true,
        );
    }

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