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

export type ProductSpecTemplate = {
  id?: string
  merchant_id?: string
  name: string
  specs: string
  attrs: string
  sort_order: number
  is_active: boolean
  created_at?: string
  updated_at?: string
}

export type ProductParamKV = {
  label: string
  value: string
}

export type ProductParamTemplate = {
  id?: string
  merchant_id?: string
  name: string
  sort_order: number
  params: ProductParamKV[]
  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
  }
}

// -------------------- Spec Templates --------------------
export async function fetchSpecTemplates(search: string | null = null): Promise<ProductSpecTemplate[]> {
  let q = supa.from('ak_product_spec_templates').select('*')
  if (search != null && search.trim() !== '') {
    q = q.ilike('name', `%${search.trim()}%`)
  }
  const { data, error } = await q.order('sort_order', { ascending: true }).execute()
  if (error != null) {
    console.error('获取规格模板失败:', error)
    return [] as ProductSpecTemplate[]
  }
  return (data ?? []) as ProductSpecTemplate[]
}

export async function saveSpecTemplate(tpl: ProductSpecTemplate): Promise<boolean> {
  const uid = getCurrentUid()
  if (uid == null) return false

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

  if (error != null) {
    console.error('保存规格模板失败:', error)
    return false
  }
  return true
}

export async function deleteSpecTemplate(id: string): Promise<boolean> {
  const { error } = await supa.from('ak_product_spec_templates').delete().eq('id', id).execute()
  if (error != null) {
    console.error('删除规格模板失败:', error)
    return false
  }
  return true
}

// -------------------- Param Templates --------------------
export async function fetchParamTemplates(search: string | null = null): Promise<ProductParamTemplate[]> {
  let q = supa.from('ak_product_param_templates').select('*')
  if (search != null && search.trim() !== '') {
    q = q.ilike('name', `%${search.trim()}%`)
  }
  const { data, error } = await q.order('sort_order', { ascending: true }).execute()
  if (error != null) {
    console.error('获取参数模板失败:', error)
    return [] as ProductParamTemplate[]
  }
  return (data ?? []) as ProductParamTemplate[]
}

export async function saveParamTemplate(tpl: ProductParamTemplate): Promise<boolean> {
  const uid = getCurrentUid()
  if (uid == null) return false

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

  if (error != null) {
    console.error('保存参数模板失败:', error)
    return false
  }
  return true
}

export async function deleteParamTemplate(id: string): Promise<boolean> {
  const { error } = await supa.from('ak_product_param_templates').delete().eq('id', id).execute()
  if (error != null) {
    console.error('删除参数模板失败:', error)
    return false
  }
  return true
}
