import { api, type ApiResponse } from './api-client'; import type { User } from '@/types'; interface AuthResponseData { userId: string; name: string; role: string; accessToken: string; refreshToken: string; } function mapUser(data: AuthResponseData): User { return { id: data.userId, phone: '', nickname: data.name, avatar: '', gender: 'unknown', birthday: '', height: 0, weight: 0, medicalHistory: [], stentImplantDate: '', createdAt: new Date().toISOString(), }; } export async function login(phone: string, smsCode: string): Promise<{ token: string; user: User }> { const res: ApiResponse = await api.post('/api/auth/login', { phone, smsCode, }); return { token: res.data.accessToken, user: mapUser(res.data) }; } export async function register(phone: string, smsCode: string, nickname: string): Promise<{ token: string; user: User }> { const res: ApiResponse = await api.post('/api/auth/register', { phone, smsCode, name: nickname, }); return { token: res.data.accessToken, user: mapUser(res.data) }; } export async function sendSmsCode(phone: string): Promise { await api.post('/api/auth/send-sms', { phone }); return true; } export async function getProfile(): Promise { const res = await api.get<{ id: string; name: string; phone: string; role: string; gender: string; birthday: string; heightCm: number; weightKg: number; medicalHistory: string[]; stentDate: string; stentType: string; department: string; title: string; specialty: string[]; introduction: string; }>('/api/auth/me'); // Update stored user info try { const raw = localStorage.getItem('hrt_auth'); if (raw) { const state = JSON.parse(raw); if (state?.state) { state.state.user = { ...state.state.user, id: res.data.id, phone: res.data.phone, nickname: res.data.name, gender: res.data.gender || 'unknown', birthday: res.data.birthday || '', height: res.data.heightCm || 0, weight: res.data.weightKg || 0, medicalHistory: res.data.medicalHistory || [], stentImplantDate: res.data.stentDate || '', }; localStorage.setItem('hrt_auth', JSON.stringify(state)); } } } catch { /* ignore */ } return res.data as unknown as User; } export async function updateProfile(data: Record): Promise { await api.put('/api/auth/me', data); } export async function logout(): Promise { localStorage.removeItem('hrt_auth'); }