// frontend/src/api/services/authService.ts - UPDATED TO HANDLE TOKENS FROM REGISTRATION import { tokenManager } from '../auth/tokenManager'; import { apiClient } from '../base/apiClient'; export interface LoginCredentials { email: string; password: string; } export interface RegisterData { email: string; password: string; full_name: string; tenant_name?: string; } export interface UserProfile { id: string; email: string; full_name: string; tenant_id?: string; role?: string; is_active: boolean; is_verified?: boolean; created_at: string; } export interface TokenResponse { access_token: string; refresh_token?: string; token_type: string; expires_in?: number; user?: UserProfile; } class AuthService { async register(data: RegisterData): Promise { // NEW: Registration now returns tokens directly - no auto-login needed! const response: TokenResponse = await apiClient.post('/api/v1/auth/register', data); // Store tokens immediately from registration response await tokenManager.storeTokens(response); // Return user profile from registration response if (response.user) { return response.user; } else { // Fallback: get user profile if not included in response return this.getCurrentUser(); } } async login(credentials: LoginCredentials): Promise { // UPDATED: Use correct endpoint and unified response handling const response: TokenResponse = await apiClient.post('/api/v1/auth/login', credentials); // Store tokens from login response await tokenManager.storeTokens(response); // Return user profile from login response if (response.user) { return response.user; } else { // Fallback: get user profile if not included in response return this.getCurrentUser(); } } async logout(): Promise { try { // Get refresh token for logout request const refreshToken = tokenManager.getRefreshToken(); if (refreshToken) { await apiClient.post('/api/v1/auth/logout', { refresh_token: refreshToken }); } } catch (error) { console.error('Logout API call failed:', error); // Continue with local cleanup even if API fails } finally { tokenManager.clearTokens(); window.location.href = '/login'; } } async getCurrentUser(): Promise { return apiClient.get('/api/v1/auth/me'); } async updateProfile(updates: Partial): Promise { return apiClient.patch('/api/v1/auth/profile', updates); } async changePassword(currentPassword: string, newPassword: string): Promise { await apiClient.post('/api/v1/auth/change-password', { current_password: currentPassword, new_password: newPassword }); } async refreshToken(): Promise { await tokenManager.refreshAccessToken(); } isAuthenticated(): boolean { return tokenManager.isAuthenticated(); } getUser(): UserProfile | null { // This method would need to be implemented to return cached user data // For now, it returns null and components should use getCurrentUser() return null; } } export const authService = new AuthService();