<?php

declare(strict_types=1);

final class MyronUpdateTemplateRailAssignmentAction implements MyronAction
{
    public function __construct(private readonly MyronRailDesignActionService $service)
    {
    }

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri: '/api/v1/design/templates/{templateId}/rail-assignment',
            method: 'PATCH',
            domain: 'design',
            resource: 'template-rail-assignment',
            verb: 'update',
            inputSchema: [
                'type' => 'object',
                'properties' => [
                    'templateId' => ['type' => 'string'],
                    'railId' => ['type' => 'string'],
                    'placement' => ['type' => 'string'],
                ],
                'required' => ['templateId', 'placement'],
            ],
            outputSchema: ['type' => 'object', 'properties' => ['templateId' => ['type' => 'string'], 'railId' => ['type' => 'string'], 'placement' => ['type' => 'string']]],
            requiredScope: MyronApiScopes::DESIGN_WRITE,
            summary: 'Assign a reusable Blog rail to a supported Blog template.',
            sideEffects: ['writes template_rail_assignments'],
            preconditions: ['template supports Blog rails'],
            postconditions: ['template resolves to selected rail and placement'],
            audienceClass: 4,
            adminAliases: ['update-template-rail-assignment', 'update-template-blog-rail'],
            snapshotInclude: false,
            exposeToMcp: true,
        );
    }

    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        try {
            return MyronActionResult::ok($this->service->setTemplateAssignment(
                (string) ($input['templateId'] ?? ''),
                (string) ($input['railId'] ?? ''),
                (string) ($input['placement'] ?? 'right'),
                $caller
            ));
        } catch (InvalidArgumentException $e) {
            return MyronActionResult::error('input_invalid', $e->getMessage());
        } catch (Throwable $e) {
            return MyronActionResult::error('business_rule_failed', $e->getMessage());
        }
    }
}
