import { callPublic } from "./base"
import { clearCookie, clearSession, readCookie, setSession } from "./token"

function parseUserInfo(raw: string | null): unknown {
  if (!raw) return null
  let decoded = raw
  try {
    decoded = decodeURIComponent(raw)
  } catch {
    decoded = raw
  }
  try {
    return JSON.parse(decoded)
  } catch {
    return decoded
  }
}

export async function apiLogin(props: {
  logincode: string
  password: string
}): Promise<{ success: boolean; message?: string }> {
  const result = await callPublic<unknown>("/user/ApiLogin", {
    Logincode: props.logincode,
    Password: props.password,
  })

  if (!result.success) {
    return { success: false, message: result.message || "用户名或者密码不正确" }
  }

  // 通过响应头下发，优先读响应头，cookie 兜底
  const token = result.headers?.token ?? readCookie("token")
  const userInfoRaw = result.headers?.userinfo ?? readCookie("userInfo")

  if (!token) {
    return { success: false, message: "登录成功但未获取到 token" }
  }

  setSession(token, parseUserInfo(userInfoRaw))

  return { success: true }
}

export async function apiRegister(props: {
  phone: string
  password: string
  code: string
  wx?: string
  qq?: string
}): Promise<{ success: boolean; message?: string }> {
  const result = await callPublic("/user/ApiRegist", {
    Code: props.code,
    Phone: props.phone,
    Pwd: props.password,
    QQ: props.qq ?? "",
    Wx: props.wx ?? "",
  })

  if (!result.success) {
    return { success: false, message: result.message }
  }

  return { success: true }
}

export async function logout() {
  clearSession()
  clearCookie("token")
  clearCookie("userInfo")
  window.location.href = "/"
}
