import { apiRequest } from '@/shared/api/client'
import type {
  CreatedIdResponse,
  JunctionAmountMode,
  JunctionConditions,
  JunctionElementKind,
  JunctionTemplateDto,
} from '@/shared/api/types'

/** Стыки общие для всех каналов — свой раздел, а не подраздел канала. */
export function listJunctions() {
  return apiRequest<JunctionTemplateDto[]>('/admin/junctions')
}

export function createJunction(name: string) {
  return apiRequest<CreatedIdResponse>('/admin/junctions', { method: 'POST', body: { name } })
}

export function updateJunction(junctionId: string, name: string, maxTotalSeconds: number | null) {
  return apiRequest<void>(`/admin/junctions/${junctionId}`, {
    method: 'PUT',
    body: { name, maxTotalSeconds },
  })
}

export function deleteJunction(junctionId: string) {
  return apiRequest<void>(`/admin/junctions/${junctionId}`, { method: 'DELETE' })
}

export function addJunctionElement(junctionId: string, kind: JunctionElementKind) {
  return apiRequest<CreatedIdResponse>(`/admin/junctions/${junctionId}/elements`, {
    method: 'POST',
    body: { kind },
  })
}

/** Тело врезки: то же для любого типа — лишние поля сервер обнуляет сам (см. JunctionElement.Update). */
export type JunctionElementBody = {
  kind: JunctionElementKind
  groupId: string | null
  bumperTemplateId: string | null
  bumperVariantId: string | null
  amountMode: JunctionAmountMode
  amountValue: number
  isRequired: boolean
  choiceKey: string | null
  choiceWeight: number
  conditions: JunctionConditions | null
}

export function updateJunctionElement(
  junctionId: string,
  elementId: string,
  body: JunctionElementBody,
) {
  return apiRequest<void>(`/admin/junctions/${junctionId}/elements/${elementId}`, {
    method: 'PUT',
    body,
  })
}

export function removeJunctionElement(junctionId: string, elementId: string) {
  return apiRequest<void>(`/admin/junctions/${junctionId}/elements/${elementId}`, {
    method: 'DELETE',
  })
}

/** Порядок и развилки едут вместе: перетаскивание в цепочке меняет и то, и другое. */
export type JunctionElementOrder = { elementId: string; choiceKey: string | null }

export function reorderJunction(junctionId: string, order: JunctionElementOrder[]) {
  return apiRequest<void>(`/admin/junctions/${junctionId}/order`, {
    method: 'PUT',
    body: { order },
  })
}
