import apiClient from '../../../shared/services/apiClient';

export interface LoginCredentials {
  email: string;
  password: string;
  rememberMe?: boolean;
  mfaToken?: string;
  expectedRole?: string;  // Optional role validation for role-specific login endpoints
}

export interface RegisterData {
  name: string;
  email: string;
  password: string;
  phone?: string;
}

export interface AuthResponse {
  
  status?: string;
  success?: boolean;
  message?: string;
  requires_mfa?: boolean;
  user_id?: number;
  data?: {
    token?: string;
    refreshToken?: string;
    user?: {
      id: number;
      name: string;
      email: string;
      phone?: string;
      avatar?: string;
      currency?: string;
      role: string;
      createdAt?: string;
    };
    secret?: string;
    qr_code?: string;
    backup_codes?: string[];
    mfa_enabled?: boolean;
    backup_codes_count?: number;
  };
}

export interface ForgotPasswordData {
  email: string;
}

export interface ResetPasswordData {
  token: string;
  password: string;
  confirmPassword: string;
}

const authService = {
  
  login: async (
    credentials: LoginCredentials
  ): Promise<AuthResponse> => {
    const response = await apiClient.post<AuthResponse>(
      '/api/auth/login',
      credentials
    );
    return response.data;
  },

  
  register: async (
    data: RegisterData
  ): Promise<AuthResponse> => {
    const response = await apiClient.post<AuthResponse>(
      '/api/auth/register',
      data
    );
    return response.data;
  },

  
  logout: async (): Promise<void> => {
    try {
      await apiClient.post('/api/auth/logout');
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error('Logout error:', error);
      }
    }
  },

  
  getProfile: async (): Promise<AuthResponse> => {
    const response = await apiClient.get<AuthResponse>(
      '/api/auth/profile'
    );
    return response.data;
  },

  
  refreshToken: async (): Promise<AuthResponse> => {
    
    const response = await apiClient.post<AuthResponse>(
      '/api/auth/refresh-token'
    );
    return response.data;
  },

  
  forgotPassword: async (
    data: ForgotPasswordData
  ): Promise<{ status?: string; success?: boolean; message?: string }> => {
    const response = await apiClient.post(
      '/api/auth/forgot-password',
      data
    );
    return response.data;
  },

  
  resetPassword: async (
    data: ResetPasswordData
  ): Promise<{ status?: string; success?: boolean; message?: string }> => {
    const response = await apiClient.post(
      '/api/auth/reset-password',
      data
    );
    return response.data;
  },

  
  updateProfile: async (
    data: {
      full_name?: string;
      email?: string;
      phone_number?: string;
      password?: string;
      currentPassword?: string;
      currency?: string;
    }
  ): Promise<AuthResponse> => {
    const response = await apiClient.put<AuthResponse>(
      '/api/auth/profile',
      data
    );
    return response.data;
  },

  
  initMFA: async (): Promise<AuthResponse> => {
    const response = await apiClient.get<AuthResponse>('/api/auth/mfa/init');
    return response.data;
  },

  
  enableMFA: async (secret: string, verificationToken: string): Promise<AuthResponse> => {
    const response = await apiClient.post<AuthResponse>('/api/auth/mfa/enable', {
      secret,
      verification_token: verificationToken
    });
    return response.data;
  },

  
  disableMFA: async (): Promise<AuthResponse> => {
    const response = await apiClient.post<AuthResponse>('/api/auth/mfa/disable');
    return response.data;
  },

  
  getMFAStatus: async (): Promise<{ mfa_enabled: boolean; backup_codes_count: number }> => {
    const response = await apiClient.get<{ mfa_enabled: boolean; backup_codes_count: number }>('/api/auth/mfa/status');
    return response.data;
  },

  
  regenerateBackupCodes: async (): Promise<AuthResponse> => {
    const response = await apiClient.post<AuthResponse>('/api/auth/mfa/regenerate-backup-codes');
    return response.data;
  },

  
  uploadAvatar: async (file: File): Promise<AuthResponse> => {
    const formData = new FormData();
    formData.append('image', file);
    
    // FormData handling: apiClient interceptor will remove Content-Type header
    // to let browser set it automatically with boundary
    const response = await apiClient.post<AuthResponse>(
      '/api/auth/avatar/upload',
      formData
    );
    return response.data;
  },
};

export default authService;
