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

/**
 * 商品标签分组模型
 */
export type ProductLabelGroup = {
  id?: string
  merchant_id?: string
  name: string
  sort_order: number
  created_at?: string
  updated_at?: string
}

/**
 * 商品标签模型
 */
export type ProductLabel = {
  id?: string
  group_id: string | null
  merchant_id?: string
  name: string
  is_active: boolean
  show_in_mobile: boolean
  sort_order: number
  created_at?: string
  updated_at?: string
}

/**
 * 获取所有标签分组
 */
export async function fetchLabelGroups(): Promise<ProductLabelGroup[]> {
  const { data, error } = await supa
    .from('ak_product_label_groups')
    .select('*')
    .order('sort_order', { ascending: true })
    .execute()

  if (error != null) {
    console.error('获取标签分组失败:', error)
    return [] as ProductLabelGroup[]
  }
  return (data ?? []) as ProductLabelGroup[]
}

/**
 * 保存标签分组（新增/更新）
 */
export async function saveLabelGroup(group: ProductLabelGroup): Promise<boolean> {
  const session = supa.getSession()
  const uid = session?.user?.getString('id')
  if (uid == null) return false

  const { error } = await supa
    .from('ak_product_label_groups')
    .upsert({
      ...group,
      merchant_id: uid,
      updated_at: new Date().toISOString()
    })
    .execute()

  if (error != null) {
    console.error('保存标签分组失败:', error)
    return false
  }
  return true
}

/**
 * 删除标签分组
 */
export async function deleteLabelGroup(id: string): Promise<boolean> {
  const { error } = await supa
    .from('ak_product_label_groups')
    .delete()
    .eq('id', id)
    .execute()

  if (error != null) {
    console.error('删除标签分组失败:', error)
    return false
  }
  return true
}

/**
 * 获取标签列表
 */
export async function fetchLabels(groupId: string | null = null): Promise<ProductLabel[]> {
  let query = supa.from('ak_product_labels').select('*')
  if (groupId != null) {
    query = query.eq('group_id', groupId)
  }
  
  const { data, error } = await query
    .order('sort_order', { ascending: true })
    .execute()

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

/**
 * 保存标签（新增/更新）
 */
export async function saveLabel(label: ProductLabel): Promise<boolean> {
  const session = supa.getSession()
  const uid = session?.user?.getString('id')
  if (uid == null) return false

  const { error } = await supa
    .from('ak_product_labels')
    .upsert({
      ...label,
      merchant_id: uid,
      updated_at: new Date().toISOString()
    })
    .execute()

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

/**
 * 删除标签
 */
export async function deleteLabel(id: string): Promise<boolean> {
  const { error } = await supa
    .from('ak_product_labels')
    .delete()
    .eq('id', id)
    .execute()

  if (error != null) {
    console.error('删除标签失败:', error)
    return false
  }
  return true
}
