import api, { ApiResponse, User, UserProfile } from './api';

export interface LoginRequest {
  email: string;
  password: string;
}

export interface RegisterRequest {
  name: string;
  email: string;
  password: string;
  password_confirmation: string;
  preferred_language?: 'en' | 'ms';
  default_industry?: string;
}

export interface AuthResponse {
  user: User;
  token: string;
}

export interface ProfileResponse {
  user: User;
  profile: UserProfile;
}

export interface UpdateProfileRequest {
  name?: string;
  preferred_language?: 'en' | 'ms';
  default_industry?: string;
}

class AuthService {
  async register(data: RegisterRequest): Promise<AuthResponse> {
    const response = await api.post<ApiResponse<AuthResponse>>('/register', data);
    
    if (!response.data.success || !response.data.data) {
      throw new Error(response.data.message || 'Registration failed');
    }
    
    const { user, token } = response.data.data;
    this.setAuthData(user, token);
    
    return response.data.data;
  }

  async login(data: LoginRequest): Promise<AuthResponse> {
    const response = await api.post<ApiResponse<AuthResponse>>('/login', data);
    
    if (!response.data.success || !response.data.data) {
      throw new Error(response.data.message || 'Login failed');
    }
    
    const { user, token } = response.data.data;
    this.setAuthData(user, token);
    
    return response.data.data;
  }

  async logout(): Promise<void> {
    try {
      await api.post('/logout');
    } catch (error) {
      // Continue with logout even if API call fails
      console.warn('Logout API call failed:', error);
    } finally {
      this.clearAuthData();
    }
  }

  async getProfile(): Promise<ProfileResponse> {
    const response = await api.get<ApiResponse<ProfileResponse>>('/profile');
    
    if (!response.data.success || !response.data.data) {
      throw new Error(response.data.message || 'Failed to get profile');
    }
    
    return response.data.data;
  }

  async updateProfile(data: UpdateProfileRequest): Promise<ProfileResponse> {
    const response = await api.put<ApiResponse<ProfileResponse>>('/profile', data);
    
    if (!response.data.success || !response.data.data) {
      throw new Error(response.data.message || 'Failed to update profile');
    }
    
    // Update stored user data
    const currentUser = this.getCurrentUser();
    if (currentUser && data.name) {
      currentUser.name = data.name;
      localStorage.setItem('user', JSON.stringify(currentUser));
    }
    
    return response.data.data;
  }

  private setAuthData(user: User, token: string): void {
    localStorage.setItem('auth_token', token);
    localStorage.setItem('user', JSON.stringify(user));
  }

  private clearAuthData(): void {
    localStorage.removeItem('auth_token');
    localStorage.removeItem('user');
  }

  isAuthenticated(): boolean {
    return !!localStorage.getItem('auth_token');
  }

  getCurrentUser(): User | null {
    const userData = localStorage.getItem('user');
    return userData ? JSON.parse(userData) : null;
  }

  getAuthToken(): string | null {
    return localStorage.getItem('auth_token');
  }
}

export const authService = new AuthService();
export default authService;