import { apiRequest } from '../lib/api'
import { getActiveBusinessId } from '../lib/businessContext'
import type { ProductVariant } from '../types/productVariant'
import type { CategoryVariationApi } from './categoryVariationsService'

export interface ProductVariantApi {
  id: string
  selections: {
    attributeId: string
    attributeName: string
    optionId: string
    value: string
  }[]
  label: string
  sortOrder: number
}

export interface CreateProductVariantPayload {
  variationId: string
  optionId: string
}

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

export function mapApiVariantToUi(item: ProductVariantApi): ProductVariant {
  return {
    id: item.id,
    selections: item.selections,
    label: item.label,
  }
}

export function mapApiVariationsToAttributes(items: CategoryVariationApi[]) {
  return items.map((item) => ({
    id: item.id,
    name: item.name,
    type: item.type,
    options: item.options,
  }))
}

export type ProductVariantAttribute = ReturnType<
  typeof mapApiVariationsToAttributes
>[number]

export async function listProductVariants(productId: string, signal?: AbortSignal) {
  const data = await apiRequest<{ items: ProductVariantApi[] }>(
    productVariantsPath(productId),
    { auth: true, signal },
  )
  return data.items.map(mapApiVariantToUi)
}

export async function createProductVariant(
  productId: string,
  payload: CreateProductVariantPayload,
) {
  const data = await apiRequest<{ message: string; variant: ProductVariantApi }>(
    productVariantsPath(productId),
    {
      method: 'POST',
      auth: true,
      body: payload,
    },
  )
  return mapApiVariantToUi(data.variant)
}

export async function deleteProductVariant(productId: string, variantId: string) {
  return apiRequest<{ message: string }>(productVariantsPath(productId, `/${variantId}`), {
    method: 'DELETE',
    auth: true,
  })
}
