<?php

declare(strict_types=1);

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

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri: '/api/v1/content/page-roles/{role}', method: 'DELETE',
            domain: 'content', resource: 'page-role', verb: 'clear',
            inputSchema: ['type' => 'object', 'properties' => ['role' => ['type' => 'string', 'enum' => MyronPageRoleService::ROLES], 'pageId' => ['type' => 'string']], 'required' => ['role']],
            outputSchema: ['type' => 'object', 'properties' => ['role' => ['type' => 'string'], 'pageId' => ['type' => ['string', 'null']], 'cleared' => ['type' => 'boolean']]],
            requiredScope: MyronApiScopes::CONTENT_WRITE,
            summary: 'Clear a singleton public page role, optionally only when a named page still holds it.',
            sideEffects: ['removes one matching site_page_roles mapping', 'invalidates public cache state when changed'],
            preconditions: ['role is home, search, or not-found'],
            postconditions: ['a matching assignment is absent', 'stale or nonmatching requests make no changes'],
            audienceClass: 4, adminAliases: ['clear-page-role'], snapshotInclude: false, exposeToMcp: true,
        );
    }

    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        try {
            return MyronActionResult::ok($this->service->clearRole((string) ($input['role'] ?? ''), isset($input['pageId']) ? (string) $input['pageId'] : null, $caller));
        } catch (InvalidArgumentException $e) {
            return MyronActionResult::error('input_invalid', $e->getMessage());
        } catch (Throwable $e) {
            return MyronActionResult::error('business_rule_failed', $e->getMessage());
        }
    }
}
