import type { ProductVariationSelection } from '../services/productVariationService'
import type { CreateStoreItemPayload } from '../services/storeItemService'
import { createId } from './id'

export interface StoreItemDraftRow {
  id: string
  storeItemId?: string
  selections: Record<string, string>
  price: string
  stock: string
  /** When true, stockQuantity is sent as null (unlimited). */
  unlimitedStock: boolean
}

/** Bulk-create: only first variation, at most this many options. */
export const BULK_CREATE_MAX_OPTIONS = 5

export function getVariationOptions(variation: ProductVariationSelection) {
  if (variation.selectedOptionIds.length > 0) {
    return variation.options.filter((option) =>
      variation.selectedOptionIds.includes(option.id),
    )
  }
  return variation.options
}

export function createEmptyStoreItemRow(): StoreItemDraftRow {
  return {
    id: createId(),
    selections: {},
    price: '',
    stock: '1',
    unlimitedStock: false,
  }
}

/** Build create payloads for bulk “add all products” (price null, stock 0). */
export function buildBulkCreateItems(
  variations: ProductVariationSelection[],
): CreateStoreItemPayload[] {
  const withOptions = variations.filter(
    (variation) => getVariationOptions(variation).length > 0,
  )

  if (withOptions.length === 0) {
    return [{ selections: [], price: null, stockQuantity: 0 }]
  }

  const first = withOptions[0]!
  const options = getVariationOptions(first).slice(0, BULK_CREATE_MAX_OPTIONS)

  return options.map((option) => ({
    selections: [{ variationId: first.id, optionId: option.id }],
    price: null,
    stockQuantity: 0,
  }))
}
