import { getApiUrl } from "../config"; import { responseErrorMessage } from "../error"; export interface LoginResponse { token: string; username: string; message?: string; } export interface AuthStatusResponse { enabled: boolean; has_users: boolean; mode?: "hub"; bootstrap_required?: boolean; registration_enabled?: boolean; } export const authApi = { login: async (username: string, password: string): Promise => { const res = await fetch(getApiUrl("/auth/login"), { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ username, password }), }); if (!res.ok) { throw new Error(await responseErrorMessage(res, "Login failed")); } return res.json(); }, register: async ( username: string, password: string, ): Promise => { const res = await fetch(getApiUrl("/auth/register"), { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ username, password }), }); if (!res.ok) { throw new Error(await responseErrorMessage(res, "Registration failed")); } return res.json(); }, getStatus: async (): Promise => { const res = await fetch(getApiUrl("/auth/status")); if (!res.ok) throw new Error("Failed to check auth status"); return res.json(); }, updateProfile: async ( currentPassword: string, newUsername?: string, newPassword?: string, ): Promise => { const token = localStorage.getItem("qwenpaw_auth_token") || ""; const res = await fetch(getApiUrl("/auth/update-profile"), { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, body: JSON.stringify({ current_password: currentPassword, new_username: newUsername || null, new_password: newPassword || null, }), }); if (!res.ok) { throw new Error(await responseErrorMessage(res, "Update failed")); } return res.json(); }, };