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

export interface ProductVariationOption {
  id: string
  label: string
  value: string
  colorHex: string | null
  sortOrder: number
}

export interface ProductVariationSelection {
  id: string
  name: string
  type: VariationType
  sortOrder: number
  options: ProductVariationOption[]
  selectedOptionIds: string[]
}

export interface ProductVariationValuesResponse {
  variations: ProductVariationSelection[]
  message?: string
}

export interface ProductVariationSelectionPayload {
  variationId: string
  optionIds: string[]
}

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

export function countSelectedOptions(variations: ProductVariationSelection[]) {
  return variations.reduce((total, variation) => total + variation.selectedOptionIds.length, 0)
}

export function selectionsToPayload(
  variations: ProductVariationSelection[],
): { selections: ProductVariationSelectionPayload[] } {
  return {
    selections: variations.map((variation) => ({
      variationId: variation.id,
      optionIds: variation.selectedOptionIds,
    })),
  }
}

export async function getProductVariationValues(productId: string, signal?: AbortSignal) {
  return apiRequest<ProductVariationValuesResponse>(businessPath(productId), {
    auth: true,
    signal,
  })
}

export async function saveProductVariationValues(
  productId: string,
  variations: ProductVariationSelection[],
) {
  return apiRequest<ProductVariationValuesResponse>(businessPath(productId), {
    method: 'PUT',
    auth: true,
    body: selectionsToPayload(variations),
  })
}
