import { apiRequest } from '../lib/api'
import { getActiveBusinessId } from '../lib/businessContext'

export interface StoreItemSelection {
  variationId: string
  variationName: string
  optionId: string
  value: string
}

export interface StoreItem {
  id: string
  storeItemId?: string
  productId: string
  productTitle: string
  productNameFa: string
  productImage: string | null
  productTotalStock: number
  selections: StoreItemSelection[]
  label: string
  price: number | null
  discountedPrice: number | null
  stockQuantity: number | null
  rewardPoints: number | null
  isFestival: boolean
  sortOrder: number
  createdAt: string
}

export interface StoreItemsListResponse {
  items: StoreItem[]
  total: number
  page: number
  pageSize: number
}

export interface CreateStoreItemPayload {
  selections: { variationId: string; optionId: string }[]
  price?: number
  stockQuantity?: number
}

export interface BatchCreateStoreItemsPayload {
  productId: string
  items: CreateStoreItemPayload[]
}

export interface UpdateStoreItemPayload {
  price?: number
  stockQuantity?: number
  discountedPrice?: number | null
  isFestival?: boolean
}

export interface BatchUpdateStoreItemDiscountsPayload {
  productId: string
  items: { id: string; discountedPrice: number | null }[]
}

export interface SyncStoreItemRowPayload {
  id?: string
  selections: { variationId: string; optionId: string }[]
  price: number
  stockQuantity: number
}

export interface SyncProductStoreItemsPayload {
  productId: string
  items: SyncStoreItemRowPayload[]
  removedIds: string[]
}

export interface BatchUpdateFestivalRewardsPayload {
  productId: string
  items: { id: string; rewardPoints: number | null }[]
}

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

export async function listStoreItems(page = 1, pageSize = 20, signal?: AbortSignal) {
  return apiRequest<StoreItemsListResponse>(
    `${businessPath()}?page=${page}&pageSize=${pageSize}`,
    { auth: true, signal },
  )
}

export async function listAllStoreItems(signal?: AbortSignal) {
  const pageSize = 100
  let page = 1
  let items: StoreItem[] = []
  let total = Infinity

  while (items.length < total) {
    const data = await listStoreItems(page, pageSize, signal)
    items = items.concat(data.items)
    total = data.total
    page += 1
  }

  return items
}

export async function batchCreateStoreItems(payload: BatchCreateStoreItemsPayload) {
  return apiRequest<{ message: string; items: StoreItem[] }>(businessPath(), {
    method: 'POST',
    auth: true,
    body: payload,
  })
}

export async function updateStoreItem(itemId: string, payload: UpdateStoreItemPayload) {
  return apiRequest<{ message: string; item: StoreItem }>(businessPath(`/${itemId}`), {
    method: 'PATCH',
    auth: true,
    body: payload,
  })
}

export async function updateStoreItemDiscounts(payload: BatchUpdateStoreItemDiscountsPayload) {
  return apiRequest<{ message: string; items: StoreItem[] }>(businessPath('/discounts'), {
    method: 'PUT',
    auth: true,
    body: payload,
  })
}

export async function syncProductStoreItems(payload: SyncProductStoreItemsPayload) {
  return apiRequest<{ message: string; items: StoreItem[] }>(businessPath('/sync'), {
    method: 'PUT',
    auth: true,
    body: payload,
  })
}

export async function updateStoreItemFestivalRewards(payload: BatchUpdateFestivalRewardsPayload) {
  return apiRequest<{ message: string; items: StoreItem[] }>(businessPath('/festival-rewards'), {
    method: 'PUT',
    auth: true,
    body: payload,
  })
}

export async function deleteStoreItem(itemId: string) {
  return apiRequest<{ message: string }>(businessPath(`/${itemId}`), {
    method: 'DELETE',
    auth: true,
  })
}

export async function deleteStoreItemsByProduct(productId: string) {
  return apiRequest<{ message: string }>(businessPath(`/by-product/${productId}`), {
    method: 'DELETE',
    auth: true,
  })
}
