<?php

declare(strict_types=1);

/**
 * APO-193 Card 8 — Service-layer for Layout token updates.
 *
 * Layout settings (container widths, gutters, breakpoints) are written to the
 * active JSONM design system layout-token record. The service delegates the
 * write to the design system registry's updateCurrentLayoutTokens method.
 *
 * DesignSystemRegistry is the JSONM-side class under
 * app/jsonm/php/lib/DesignSystemRegistry.php (un-prefixed, lives in the JSONM
 * runtime); the service owns the lazy require so the admin route does not
 * need to load it explicitly when invoking through the service.
 */
final class MyronLayoutActionService
{
    public function __construct(
        private readonly object $registry,
    ) {
    }

    /**
     * @param array<string, mixed> $layout
     * @return array{recordName: string, recordId: string}
     */
    public function updateLayout(array $layout, MyronActionCallerContext $caller): array
    {
        if ($layout === []) {
            throw new InvalidArgumentException('layout payload is required.');
        }
        if (!method_exists($this->registry, 'updateCurrentLayoutTokens')) {
            throw new MyronActionPreconditionError('Design system registry does not support updateCurrentLayoutTokens.');
        }
        $record = (array) $this->registry->updateCurrentLayoutTokens($layout);
        return [
            'recordName' => (string) ($record['name'] ?? ''),
            'recordId'   => (string) ($record['id'] ?? ''),
        ];
    }
}
