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

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

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

  const token = readCookie("token")
  const userInfoRaw = readCookie("userInfo")

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

  let userInfo: unknown = userInfoRaw
  if (userInfoRaw) {
    try {
      userInfo = JSON.parse(userInfoRaw)
    } catch {
      userInfo = userInfoRaw
    }
  }

  setSession(token, userInfo)

  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()
  window.location.href = "/"
}
