import { apiRequest } from '../lib/api'
import { getActiveBusinessId } from '../lib/businessContext'
import type { Variation, VariationType } from '../types/variation'

export interface CategoryVariationApi {
  id: string
  name: string
  type: VariationType
  sortOrder: number
  values: string[]
  options: {
    id: string
    label: string
    value: string
    colorHex: string | null
    sortOrder: number
  }[]
}

export interface ColorPreset {
  name: string
  hex: string
}

function businessPath(suffix = '') {
  const businessId = getActiveBusinessId()
  if (!businessId) {
    throw new Error('No active business selected. Please sign in again.')
  }
  return `/businesses/${businessId}/categories${suffix}`
}

export function mapApiVariationToUi(item: CategoryVariationApi): Variation {
  return {
    id: item.id,
    name: item.name,
    type: item.type,
    values: item.values,
  }
}

export async function listColorPresets(signal?: AbortSignal) {
  const data = await apiRequest<{ items: ColorPreset[] }>(businessPath('/color-presets'), {
    auth: true,
    signal,
  })
  return data.items
}

export async function listCategoryVariations(categoryId: string, signal?: AbortSignal) {
  const data = await apiRequest<{ items: CategoryVariationApi[] }>(
    businessPath(`/${categoryId}/variations`),
    { auth: true, signal },
  )
  return data.items.map(mapApiVariationToUi)
}

export async function fetchCategoryVariations(categoryId: string, signal?: AbortSignal) {
  const data = await apiRequest<{ items: CategoryVariationApi[] }>(
    businessPath(`/${categoryId}/variations`),
    { auth: true, signal },
  )
  return data.items
}

export async function saveCategoryVariations(
  categoryId: string,
  variations: Variation[],
) {
  const data = await apiRequest<{ items: CategoryVariationApi[] }>(
    businessPath(`/${categoryId}/variations`),
    {
      method: 'PUT',
      auth: true,
      body: {
        variations: variations.map((variation) => ({
          type: variation.type,
          name: variation.name,
          values: variation.values,
        })),
      },
    },
  )
  return data.items.map(mapApiVariationToUi)
}
