<?php

declare(strict_types=1);

final class MyronRailDesignActionService
{
    public function __construct(private readonly MyronRailDesignRepository $rails)
    {
    }

    /**
     * @return array<string, mixed>
     */
    public function updateRail(string $railId, array $settings, MyronActionCallerContext $caller): array
    {
        return $this->rails->saveConfiguration($railId, $settings, $this->callerUserId($caller));
    }

    /**
     * @return array{railId:string,previousDefault:string}
     */
    public function setDefault(string $railId, MyronActionCallerContext $caller): array
    {
        $railId = $this->rails->normalizeRailId($railId);
        $previousDefault = (string) ($this->rails->getDefault()['rail_id'] ?? '');
        $this->rails->setDefault($railId, $this->callerUserId($caller));
        return ['railId' => $railId, 'previousDefault' => $previousDefault];
    }

    /**
     * @return array{templateId:string,railId:string,placement:string}
     */
    public function setTemplateAssignment(string $sourceTemplateId, ?string $railId, string $placement, MyronActionCallerContext $caller): array
    {
        $normalizedRailId = $railId === null || trim($railId) === '' ? MyronRailDesignRepository::DEFAULT_RAIL : $this->rails->normalizeRailId($railId);
        $normalizedPlacement = $this->rails->normalizePlacement($placement);
        $this->rails->setTemplateAssignment($sourceTemplateId, $normalizedRailId, $normalizedPlacement, $this->callerUserId($caller));
        return [
            'templateId' => trim($sourceTemplateId),
            'railId' => $normalizedRailId,
            'placement' => $normalizedPlacement,
        ];
    }

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