File size: 2,676 Bytes
da8e27d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
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<string, unknown> | 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<LoginResponse> {
  try {
    const { data } = await axios.post<LoginResponse>(`${API_BASE}/auth/login`, payload)
    return data
  } catch (err) {
    normalizeError(err)
  }
}

export async function register(payload: RegisterRequest): Promise<RegisterResponse> {
  try {
    const { data } = await axios.post<RegisterResponse>(`${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)
  }
}