<?php

declare(strict_types=1);

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

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri: '/api/v1/content/pages', method: 'POST',
            domain: 'content', resource: 'page', verb: 'create',
            inputSchema: [
                'type' => 'object',
                'properties' => [
                    'templateId'      => ['type' => 'string'],
                    'name'            => ['type' => 'string'],
                    'slug'            => ['type' => 'string'],
                    'parentPageId'    => ['type' => 'string'],
                    'seoTitle'        => ['type' => 'string'],
                    'metaDescription' => ['type' => 'string'],
                    'content'         => ['type' => 'object'],
                    'categoryIds'     => ['type' => 'array', 'items' => ['type' => 'string']],
                    'includeInNav'     => ['type' => 'boolean'],
                    'author'          => [
                        'type' => 'object',
                        'properties' => [
                            'authorName' => ['type' => 'string'],
                            'authorUserId' => ['type' => 'string'],
                            'avatarFileId' => ['type' => 'string'],
                            'bio' => ['type' => 'string'],
                        ],
                    ],
                    'publish'         => ['type' => 'boolean'],
                    'publishedAt'     => ['type' => 'string'],
                ],
                'required' => ['templateId', 'name'],
            ],
            outputSchema: ['type' => 'object', 'properties' => ['pageId' => ['type' => 'string']]],
            requiredScope: MyronApiScopes::CONTENT_WRITE,
            summary: 'Create a page bound to a template. Provide content as a section-keyed object; publish:true to publish immediately, false for draft.',
            sideEffects: ['inserts pages row', 'inserts page_versions row'],
            preconditions: ['templateId references an existing template'],
            postconditions: ['page row created; draft or published per input'],
            audienceClass: 4,
            adminAliases: ['save-draft'],
            snapshotInclude: false,
            exposeToMcp: true,
        );
    }

    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        try {
            $content = is_array($input['content'] ?? null) ? (array) $input['content'] : [];
            $categoryIds = is_array($input['categoryIds'] ?? null) ? array_values(array_map('strval', (array) $input['categoryIds'])) : [];
            $author = is_array($input['author'] ?? null) ? (array) $input['author'] : [];
            return MyronActionResult::ok($this->service->create(
                (string) ($input['templateId'] ?? ''),
                (string) ($input['name'] ?? ''),
                (string) ($input['slug'] ?? ''),
                isset($input['parentPageId']) ? (string) $input['parentPageId'] : null,
                (string) ($input['seoTitle'] ?? ''),
                (string) ($input['metaDescription'] ?? ''),
                $content,
                (bool) ($input['publish'] ?? false),
                isset($input['publishedAt']) ? (string) $input['publishedAt'] : null,
                null,
                null,
                $caller,
                [],
                $categoryIds,
                $author,
                array_key_exists('includeInNav', $input) ? $this->normalizeBoolean($input['includeInNav']) : null
            ));
        } 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());
        }
    }

    private function normalizeBoolean(mixed $value): bool
    {
        if (is_bool($value)) {
            return $value;
        }

        $normalized = strtolower(trim((string) $value));
        return in_array($normalized, ['1', 'true', 'yes', 'on'], true);
    }
}
