import supa from '@/components/supadb/aksupainstance.uts'

export type UserLevel = {
  id: string
  name: string
  level_weight: number
  discount_percent: number
  is_visible: boolean
  status: number
  deleted_at: string | null
}

export type ProductSku = {
  id: string
  product_id: string
  sku_code: string
  specifications: any
  price: number
  stock: number
  status: number
  image_url: string | null
}

export type ProductMemberPrice = {
  id?: string
  merchant_id?: string
  product_id: string
  sku_id: string
  level_id: string
  member_price: number
  created_at?: string
  updated_at?: string
}

export type MemberPriceMatrixRow = {
  sku: ProductSku
  pricesByLevel: Record<string, number | null>
}

function getCurrentUid(): string | null {
  try {
    const session = supa.getSession()
    const uid = session?.user?.getString('id')
    return uid ?? null
  } catch (e) {
    return null
  }
}

export async function fetchActiveUserLevels(): Promise<UserLevel[]> {
  const { data, error } = await supa
    .from('ak_user_levels')
    .select('id,name,level_weight,discount_percent,is_visible,status,deleted_at')
    .is('deleted_at', null)
    .eq('status', 1)
    .eq('is_visible', true)
    .order('level_weight', { ascending: true })
    .execute()

  if (error != null) {
    console.error('获取会员等级失败:', error)
    return [] as UserLevel[]
  }
  return (data ?? []) as UserLevel[]
}

export async function fetchProductSkus(productId: string): Promise<ProductSku[]> {
  const { data, error } = await supa
    .from('ml_product_skus')
    .select('id,product_id,sku_code,specifications,price,stock,status,image_url')
    .eq('product_id', productId)
    .order('created_at', { ascending: true })
    .execute()

  if (error != null) {
    console.error('获取 SKU 失败:', error)
    return [] as ProductSku[]
  }
  return (data ?? []) as ProductSku[]
}

export async function fetchMemberPrices(productId: string): Promise<ProductMemberPrice[]> {
  const { data, error } = await supa
    .from('ak_product_member_prices')
    .select('id,product_id,sku_id,level_id,member_price,created_at,updated_at')
    .eq('product_id', productId)
    .execute()

  if (error != null) {
    console.error('获取会员价失败:', error)
    return [] as ProductMemberPrice[]
  }
  return (data ?? []) as ProductMemberPrice[]
}

export async function saveMemberPrices(productId: string, rows: Array<{ sku_id: string; level_id: string; member_price: number }>): Promise<boolean> {
  const uid = getCurrentUid()
  if (uid == null) return false

  const payload = rows.map(r => ({
    merchant_id: uid,
    product_id: productId,
    sku_id: r.sku_id,
    level_id: r.level_id,
    member_price: r.member_price,
    updated_at: new Date().toISOString()
  }))

  const { error } = await supa
    .from('ak_product_member_prices')
    .upsert(payload as any)
    .execute()

  if (error != null) {
    console.error('保存会员价失败:', error)
    return false
  }
  return true
}
