<?php

declare(strict_types=1);

/**
 * APO-193 Card 8 — Update layout settings.
 *
 * URI:   PATCH /api/v1/design/layout
 * Scope: design.write
 */
final class MyronUpdateLayoutAction implements MyronAction
{
    public function __construct(
        private readonly MyronLayoutActionService $service,
    ) {
    }

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri:           '/api/v1/design/layout',
            method:        'PATCH',
            domain:        'design',
            resource:      'layout',
            verb:          'update',
            inputSchema:   [
                'type'       => 'object',
                'properties' => [
                    'layout' => ['type' => 'object'],
                ],
                'required'   => ['layout'],
            ],
            outputSchema:  [
                'type'       => 'object',
                'properties' => [
                    'recordName' => ['type' => 'string'],
                    'recordId'   => ['type' => 'string'],
                ],
            ],
            requiredScope:   MyronApiScopes::DESIGN_WRITE,
            summary:         'Update site-wide layout tokens (container widths, gutters, breakpoints) on the install\'s active JSONM design definition. Layout tokens are a sub-slice of the design token surface.',
            sideEffects:     ['writes layout tokens on active JSONM design definition'],
            preconditions:   ['active JSONM design definition exists'],
            postconditions:  ['active record reflects new layout settings'],
            audienceClass:   4,
            adminAliases:    ['update-layout'],
            snapshotInclude: false,
            exposeToMcp:     true,
        );
    }

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