<?php

declare(strict_types=1);

/**
 * APO-194 Card 5 — Template Chrome Assignment action service.
 *
 * Binds a navigation version + footer variant to a specific template's
 * source_template_id. Both the admin form path (site-type-studio.php and
 * templates-manager.php — same verb name, shared business logic) and the API
 * path POST /api/v1/design/templates/{templateId}/chrome funnel through this
 * service. Reset clears the assignment (template falls back to global default).
 */
final class MyronTemplateChromeActionService
{
    public function __construct(
        private readonly MyronTemplateChromeAssignmentRepository $repository,
    ) {
    }

    /**
     * @return array{templateId: string, navigationDesignId: string, footerVariantId: ?string}
     */
    public function assign(
        string $templateId,
        string $navigationDesignId,
        ?string $footerVariantId,
        MyronActionCallerContext $caller
    ): array {
        $templateId = trim($templateId);
        if ($templateId === '') {
            throw new InvalidArgumentException('templateId is required.');
        }
        $assignment = [
            'navigation_design_id' => trim($navigationDesignId),
            'footer_variant_id'    => $footerVariantId !== null ? trim($footerVariantId) : null,
        ];
        $this->repository->setForTemplate($templateId, $assignment, $this->callerUserId($caller));
        return [
            'templateId'         => $templateId,
            'navigationDesignId' => $assignment['navigation_design_id'],
            'footerVariantId'    => $assignment['footer_variant_id'],
        ];
    }

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

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