import axios, { AxiosError } from 'axios' const API_BASE = '/api' // ── Request / Response types ────────────────────────────────────────────────── export interface LoginRequest { email: string password: string } export interface LoginResponse { access_token: string token_type: 'bearer' user: { id: string email: string full_name: string role: 'doctor' | 'admin' } } export interface RegisterRequest { full_name: string email: string password: string confirm_password: string } export interface RegisterResponse { message: string // "Đăng ký thành công. Vui lòng kiểm tra email để xác thực tài khoản." } export interface ForgotPasswordRequest { email: string } // ── Error normalizer ────────────────────────────────────────────────────────── function normalizeError(err: unknown): never { if (err instanceof AxiosError) { if (!err.response) { throw new Error( 'Không thể kết nối đến máy chủ (cổng 8000). ' + 'Vui lòng khởi động Python Backend Server rồi thử lại.', ) } const body = err.response.data as Record | undefined const detail = (body?.detail as string | undefined) ?? (body?.message as string | undefined) ?? (body?.error as string | undefined) ?? err.message throw new Error(detail) } throw err } // ── API functions ───────────────────────────────────────────────────────────── export async function login(payload: LoginRequest): Promise { try { const { data } = await axios.post(`${API_BASE}/auth/login`, payload) return data } catch (err) { normalizeError(err) } } export async function register(payload: RegisterRequest): Promise { try { const { data } = await axios.post(`${API_BASE}/auth/register`, payload) return data } catch (err) { normalizeError(err) } } export async function forgotPassword(payload: ForgotPasswordRequest): Promise<{ message: string }> { try { const { data } = await axios.post<{ message: string }>( `${API_BASE}/auth/forgot-password`, payload, ) return data } catch (err) { normalizeError(err) } }