import client from "./client"
import type { CaptchaResult } from "../utils/geetest"

export interface RewardChannelSummary {
  count: number
  points: number
}

export interface PointCenterOverview {
  available_points: number
  balance_cents: number
  qq_rewarded: boolean
  bilibili_rewarded: boolean
  today_checkin: number | null
  self_purchase: RewardChannelSummary
  member_commission: RewardChannelSummary
  agent_profit: RewardChannelSummary
  settings: {
    qq_reward: number
    bilibili_reward: number
    checkin_min_points: number
    checkin_max_points: number
    withdraw_fee_rate: number
    withdraw_min_points: number
  }
  recent_withdrawals: {
    id: number
    points_amount: number
    fee_points: number
    credited_cents: number
    status: string
    created_at: string | null
  }[]
}

export async function getPointCenterOverview() {
  const res = await client.get("/v1/points/center")
  const data = (res.data.data ?? {}) as Partial<PointCenterOverview>
  const settings = data.settings ?? {
    qq_reward: 0,
    bilibili_reward: 0,
    checkin_min_points: 0,
    checkin_max_points: 0,
    withdraw_fee_rate: 0,
    withdraw_min_points: 0,
  }
  return {
    available_points: Number(data.available_points ?? 0) || 0,
    balance_cents: Number(data.balance_cents ?? 0) || 0,
    qq_rewarded: Boolean(data.qq_rewarded),
    bilibili_rewarded: Boolean(data.bilibili_rewarded),
    today_checkin: data.today_checkin ?? null,
    self_purchase: data.self_purchase ?? { count: 0, points: 0 },
    member_commission: data.member_commission ?? { count: 0, points: 0 },
    agent_profit: data.agent_profit ?? { count: 0, points: 0 },
    settings,
    recent_withdrawals: Array.isArray(data.recent_withdrawals) ? data.recent_withdrawals : [],
  }
}

export async function completeQQTask(answer: string) {
  const res = await client.post("/v1/points/tasks/qq", { answer })
  return res.data.data as { reward_points: number; available_points: number }
}

export async function completeBilibiliTask(answer: string) {
  const res = await client.post("/v1/points/tasks/bilibili", { answer })
  return res.data.data as { reward_points: number; available_points: number }
}

export async function dailyCheckin(captcha: CaptchaResult | null) {
  const res = await client.post("/v1/points/tasks/checkin", { captcha })
  return res.data.data as { reward_points: number; available_points: number }
}

export async function withdrawPoints(points: number) {
  const res = await client.post("/v1/points/withdraw", { points })
  return res.data.data as {
    available_points: number
    balance_cents: number
    points_amount: number
    fee_points: number
    credited_cents: number
  }
}
