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

/**
 * Admin 店铺列表项（对应 ml_shops 列表页所需字段）
 */
export type AdminShopItem = {
  id: string
  cid: number
  merchant_id: string
  shop_name: string
  shop_logo: string | null
  contact_name: string | null
  contact_phone: string | null
  status: number
  product_count: number
  order_count: number
  rating_avg: number
  rating_count: number
  verified_at: string | null
  created_at: string
}

/**
 * Admin 店铺查询参数
 */
export type AdminShopQuery = {
  searchName?: string | null
  status?: number | null
  startTime?: string | null
  endTime?: string | null
  page?: number
  pageSize?: number
}

// 精确选取列表页需要字段，禁止 SELECT *
const LIST_COLUMNS = 'id,cid,merchant_id,shop_name,shop_logo,contact_name,contact_phone,status,product_count,order_count,rating_avg,rating_count,verified_at,created_at'

/**
 * 分页查询 ml_shops（服务端分页，按需按页请求）
 */
export async function fetchAdminShops(query?: AdminShopQuery): Promise<{ total: number; items: Array<AdminShopItem> }> {
  const page = query?.page ?? 1
  const pageSize = query?.pageSize ?? 20

  const builder = supa
    .from('ml_shops')
    .select(LIST_COLUMNS)
    .order('created_at', { ascending: false })
    .limit(pageSize)
    .page(page)

  // 条件过滤（仅非空时才附加，避免无效 filter）
  if (query?.status != null) {
    builder.eq('status', query.status)
  }
  if (query?.searchName != null && query.searchName !== '') {
    builder.ilike('shop_name', `%${query.searchName}%`)
  }
  if (query?.startTime != null && query.startTime !== '') {
    builder.gte('created_at', query.startTime)
  }
  if (query?.endTime != null && query.endTime !== '') {
    builder.lte('created_at', query.endTime)
  }

  const result = await builder.execute()

  if (result.error != null) {
    console.error('[shopManageService] fetchAdminShops 失败:', result.error)
    return { total: 0, items: [] as Array<AdminShopItem> }
  }

  const rawRows = (result.data ?? []) as any[]
  const items: Array<AdminShopItem> = []

  for (let i = 0; i < rawRows.length; i++) {
    const row = rawRows[i] as UTSJSONObject
    items.push({
      id: row.getString('id') ?? '',
      cid: row.getNumber('cid') ?? 0,
      merchant_id: row.getString('merchant_id') ?? '',
      shop_name: row.getString('shop_name') ?? '',
      shop_logo: row.getString('shop_logo') ?? null,
      contact_name: row.getString('contact_name') ?? null,
      contact_phone: row.getString('contact_phone') ?? null,
      status: row.getNumber('status') ?? 1,
      product_count: row.getNumber('product_count') ?? 0,
      order_count: row.getNumber('order_count') ?? 0,
      rating_avg: row.getNumber('rating_avg') ?? 0,
      rating_count: row.getNumber('rating_count') ?? 0,
      verified_at: row.getString('verified_at') ?? null,
      created_at: row.getString('created_at') ?? ''
    } as AdminShopItem)
  }

  return { total: result.total ?? 0, items }
}

/**
 * 更新指定店铺的状态（1=正常 2=暂停 3=关闭）
 */
export async function updateAdminShopStatus(shopId: string, status: number): Promise<boolean> {
  const result = await supa
    .from('ml_shops')
    .update({ status: status, updated_at: new Date().toISOString() } as UTSJSONObject)
    .eq('id', shopId)
    .execute()

  if (result.error != null) {
    console.error('[shopManageService] updateAdminShopStatus 失败:', result.error)
    return false
  }
  return true
}
