<?php

declare(strict_types=1);

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

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri: '/api/v1/content/pages/{pageId}/categories',
            method: 'PATCH',
            domain: 'content',
            resource: 'page-categories',
            verb: 'set',
            inputSchema: [
                'type' => 'object',
                'properties' => [
                    'pageId' => ['type' => 'string'],
                    'categoryIds' => ['type' => 'array', 'items' => ['type' => 'string']],
                ],
                'required' => ['pageId', 'categoryIds'],
            ],
            outputSchema: ['type' => 'object', 'properties' => ['pageId' => ['type' => 'string'], 'categories' => ['type' => 'array']]],
            requiredScope: MyronApiScopes::CONTENT_WRITE,
            summary: 'Replace the category assignments for a page with a validated list of active category IDs.',
            sideEffects: ['updates page_category_assignments rows'],
            preconditions: ['page exists', 'all categoryIds reference active categories'],
            postconditions: ['page category assignments match categoryIds'],
            audienceClass: 4,
            snapshotInclude: false,
            exposeToMcp: true,
        );
    }

    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        try {
            $categoryIds = is_array($input['categoryIds'] ?? null) ? array_values(array_map('strval', (array) $input['categoryIds'])) : [];
            return MyronActionResult::ok($this->service->setCategories((string) ($input['pageId'] ?? ''), $categoryIds, $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());
        }
    }
}
