import client from "./client"

export interface MemberLevel {
  id: number
  name: string
  level: number
  min_total_spent: number
  self_discount_rate: number
  points_multiplier: number
  commission_rate: number
  points_cashback_rate?: number
  self_spent_threshold_current_quarter?: number
  downline_spent_threshold_90d?: number
  eligible_agent_tier?: string | null
  max_points_discount_rate: number
  can_apply_agent: boolean
  sort_order: number
  enabled: boolean
}

export interface UserMembership {
  user_id: number
  member_level_id: number | null
  member_level_locked: boolean
  agent_tier: "yunqi" | "yunxiang" | "yunce" | "yunling" | "yunzun" | "yunguan" | null
  commission_rate: number
  total_spent: number
  current_quarter_spent?: number
  current_quarter_self_spent?: number
  downline_spent_90d?: number
  downline_spent_last_90d?: number
  total_points: number
  available_points: number
  upgraded_at: string | null
  member_level: MemberLevel | null
}

export interface PointLog {
  id: number
  user_id: number
  change_type: string
  delta: number
  balance_after: number
  order_id: number | null
  ref_no: string | null
  remark: string | null
  created_at: string
}

export async function getMemberLevels() {
  const res = await client.get("/v1/membership/levels")
  return Array.isArray(res.data.data) ? res.data.data as MemberLevel[] : []
}

export async function getMyMembership() {
  const res = await client.get("/v1/membership/me")
  return res.data.data as UserMembership
}

export async function getPointLogs(limit = 20, offset = 0) {
  const res = await client.get("/v1/membership/points/logs", {
    params: { limit, offset },
  })
  return Array.isArray(res.data.data) ? res.data.data as PointLog[] : []
}
