// 账号体系前端封装：token 存储 + 注册/登录/当前用户
// 与后端 /api/auth/* 交互（JWT 无状态，token 存 localStorage）

const API_BASE = ((import.meta as any).env?.PUBLIC_API_BASE ?? "").replace(/\/$/, "")
const TOKEN_KEY = "fa_token"
const USER_KEY = "fa_user"

export type AuthUser = { id: number; username: string; email: string }

export function getToken(): string | null {
  return localStorage.getItem(TOKEN_KEY)
}

export function getUser(): AuthUser | null {
  const raw = localStorage.getItem(USER_KEY)
  if (!raw) return null
  try {
    return JSON.parse(raw) as AuthUser
  } catch {
    return null
  }
}

export function setSession(token: string, user: AuthUser) {
  localStorage.setItem(TOKEN_KEY, token)
  localStorage.setItem(USER_KEY, JSON.stringify(user))
}

export function clearSession() {
  localStorage.removeItem(TOKEN_KEY)
  localStorage.removeItem(USER_KEY)
}

export async function login(account: string, password: string): Promise<AuthUser> {
  const res = await fetch(`${API_BASE}/api/auth/login`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ account, password }),
  })
  const json: any = await res.json().catch(() => ({}))
  if (!res.ok) throw new Error(json?.error || "登录失败")
  setSession(json.token, json.user)
  return json.user as AuthUser
}

export async function register(
  username: string,
  email: string,
  password: string
): Promise<AuthUser> {
  const res = await fetch(`${API_BASE}/api/auth/register`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ username, email, password }),
  })
  const json: any = await res.json().catch(() => ({}))
  if (!res.ok) throw new Error(json?.error || "注册失败")
  setSession(json.token, json.user)
  return json.user as AuthUser
}

// 用本地 token 拉取最新用户信息（校验有效性）；无效则清空会话
export async function fetchMe(): Promise<AuthUser | null> {
  const token = getToken()
  if (!token) return null
  try {
    const res = await fetch(`${API_BASE}/api/auth/me`, {
      headers: { Authorization: `Bearer ${token}` },
    })
    if (!res.ok) {
      clearSession()
      return null
    }
    const json: any = await res.json()
    const user = json?.user as AuthUser
    if (user) localStorage.setItem(USER_KEY, JSON.stringify(user))
    return user
  } catch {
    return getUser()
  }
}

// 带鉴权头的请求头（供将来受保护接口使用）
export function authHeaders(): Record<string, string> {
  const t = getToken()
  return t ? { Authorization: `Bearer ${t}` } : {}
}
