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

export type ProductProtection = {
  id?: string
  merchant_id?: string
  name: string
  description: string
  icon_url: string | null
  sort_order: number
  is_active: boolean
  created_at?: string
  updated_at?: string
}

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 fetchProductProtections(): Promise<ProductProtection[]> {
  const { data, error } = await supa
    .from('ak_product_protections')
    .select('*')
    .order('sort_order', { ascending: true })
    .execute()

  if (error != null) {
    console.error('获取商品保障失败:', error)
    return [] as ProductProtection[]
  }
  return (data ?? []) as ProductProtection[]
}

export async function saveProductProtection(item: ProductProtection): Promise<boolean> {
  const uid = getCurrentUid()
  if (uid == null) return false

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

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

export async function deleteProductProtection(id: string): Promise<boolean> {
  const { error } = await supa
    .from('ak_product_protections')
    .delete()
    .eq('id', id)
    .execute()

  if (error != null) {
    console.error('删除商品保障失败:', error)
    return false
  }
  return true
}

export async function setProductProtectionActive(id: string, isActive: boolean): Promise<boolean> {
  const { error } = await supa
    .from('ak_product_protections')
    .update({ is_active: isActive, updated_at: new Date().toISOString() })
    .eq('id', id)
    .execute()

  if (error != null) {
    console.error('更新商品保障状态失败:', error)
    return false
  }
  return true
}
