<?php

declare(strict_types=1);

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

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri: '/api/v1/content/page-roles/{role}', method: 'PUT',
            domain: 'content', resource: 'page-role', verb: 'assign',
            inputSchema: ['type' => 'object', 'properties' => ['role' => ['type' => 'string', 'enum' => MyronPageRoleService::ROLES], 'pageId' => ['type' => 'string']], 'required' => ['role', 'pageId']],
            outputSchema: ['type' => 'object', 'properties' => ['role' => ['type' => 'string'], 'pageId' => ['type' => 'string'], 'changed' => ['type' => 'boolean']]],
            requiredScope: MyronApiScopes::CONTENT_WRITE,
            summary: 'Assign a singleton public page role, atomically moving it from any previous holder.',
            sideEffects: ['moves one site_page_roles mapping', 'invalidates public cache state when changed'],
            preconditions: ['role is home, search, or not-found', 'page exists'],
            postconditions: ['the requested page is the sole holder of the role', 'page identity, content, and publication state are unchanged'],
            audienceClass: 4, adminAliases: ['assign-page-role'], snapshotInclude: false, exposeToMcp: true,
        );
    }

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