<?php

declare(strict_types=1);

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

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri: '/api/v1/content/pages/{pageId}/nav-visibility',
            method: 'PATCH',
            domain: 'content',
            resource: 'page-nav-visibility',
            verb: 'set',
            inputSchema: [
                'type' => 'object',
                'properties' => [
                    'pageId' => ['type' => 'string'],
                    'includeInNav' => ['type' => 'boolean'],
                ],
                'required' => ['pageId', 'includeInNav'],
            ],
            outputSchema: ['type' => 'object', 'properties' => ['pageId' => ['type' => 'string'], 'includeInNav' => ['type' => 'boolean']]],
            requiredScope: MyronApiScopes::CONTENT_WRITE,
            summary: 'Set whether a page appears as an auto-expanded public navigation descendant without changing unrelated page content.',
            sideEffects: ['updates pages.include_in_nav'],
            preconditions: ['page exists'],
            postconditions: ['page navigation visibility matches includeInNav'],
            audienceClass: 4,
            snapshotInclude: false,
            exposeToMcp: true,
        );
    }

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

    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);
    }
}
