import type { User } from "@/lib/types" import { httpJson } from "./http" export type RegisterInput = { username: string email: string password: string vcode?: string requestId?: string } export type LoginInput = { username: string password: string } function throwApiError(code: number, msg: string): never { throw { code, msg } } export async function register(input: RegisterInput): Promise { const username = input.username.trim() const email = input.email.trim() const password = input.password const vcode = input.vcode?.trim() if (!username) throwApiError(400, "请输入用户名") if (!email) throwApiError(400, "请输入邮箱") if (!password || password.length < 6) throwApiError(400, "密码至少6位") const headers: Record = {} if (input.requestId) headers["X-Request-Id"] = input.requestId const res = await httpJson<{ user: User }>("/api/v1/auth/register", { method: "POST", json: { username, email, password, vcode }, headers, }) return res.user } export async function login(input: LoginInput): Promise { const username = input.username.trim() const password = input.password if (!username) throwApiError(400, "请输入用户名") if (!password || password.length < 6) throwApiError(400, "密码至少6位") const res = await httpJson<{ user: User }>("/api/v1/auth/login", { method: "POST", json: { username, password }, }) return res.user } export async function logout(): Promise { await httpJson("/api/v1/auth/logout", { method: "POST", }) } export async function resetPassword(input: { email: string vcode: string newPassword: string requestId?: string }): Promise { const email = input.email.trim() const vcode = input.vcode.trim() const newPassword = input.newPassword if (!email) throwApiError(400, "请输入邮箱") if (!vcode) throwApiError(400, "请输入验证码") if (!newPassword || newPassword.length < 8) throwApiError(400, "密码至少8位") const headers: Record = {} if (input.requestId) headers["X-Request-Id"] = input.requestId await httpJson("/api/v1/auth/reset-password", { method: "POST", json: { email, vcode, newPassword }, headers, }) }