<?php

declare(strict_types=1);

/**
 * APO-193 Card 7 — Section Variant action service.
 *
 * Saved section variants are operator-curated section configurations that can
 * be applied across pages. Three verbs: create, update, delete. Both the
 * admin form path and the /api/v1/design/section-variants/... API path funnel
 * through this service.
 */
final class MyronSectionVariantActionService
{
    public function __construct(
        private readonly MyronSectionVariantRepository $variants,
    ) {
    }

    /**
     * @param array<string, mixed> $design
     * @param array<string, mixed> $content
     * @return array<string, mixed>
     */
    public function create(
        string $name,
        string $sectionKey,
        string $componentId,
        string $variant,
        array $design,
        array $content,
        MyronActionCallerContext $caller
    ): array {
        $name = trim($name);
        if ($name === '') {
            throw new InvalidArgumentException('name is required.');
        }
        $componentId = trim($componentId);
        if ($componentId === '') {
            throw new InvalidArgumentException('componentId is required.');
        }
        return (array) $this->variants->createVariant(
            $name,
            trim($sectionKey),
            $componentId,
            trim($variant) !== '' ? trim($variant) : 'default',
            $design,
            $content,
            $this->callerUserId($caller)
        );
    }

    /**
     * @param array<string, mixed> $design
     * @param array<string, mixed> $content
     * @return array<string, mixed>
     */
    public function update(
        string $variantId,
        string $name,
        string $sectionKey,
        string $componentId,
        string $variant,
        array $design,
        array $content,
        MyronActionCallerContext $caller
    ): array {
        $variantId = trim($variantId);
        if ($variantId === '') {
            throw new InvalidArgumentException('variantId is required.');
        }
        return (array) $this->variants->updateVariant(
            $variantId,
            trim($name),
            trim($sectionKey),
            trim($componentId),
            trim($variant) !== '' ? trim($variant) : 'default',
            $design,
            $content
        );
    }

    /**
     * @return array{variantId: string, deleted: bool}
     */
    public function delete(string $variantId, MyronActionCallerContext $caller): array
    {
        $variantId = trim($variantId);
        if ($variantId === '') {
            throw new InvalidArgumentException('variantId is required.');
        }
        $this->variants->delete($variantId);
        return ['variantId' => $variantId, 'deleted' => true];
    }

    private function callerUserId(MyronActionCallerContext $caller): string
    {
        return $caller->callerType === 'human-session' ? $caller->callerId : '';
    }
}
