import axios from 'axios';

// Create axios instance with base configuration
const api = axios.create({
  baseURL: 'https://test-rwa-service.hicoinpay.com',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// Request interceptor to add auth token
api.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('authToken');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// Response interceptor to handle common errors
api.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    if (error.response?.status === 401) {
      // Handle unauthorized access
      localStorage.removeItem('authToken');
      window.location.href = '/login';
    }
    return Promise.reject(error);
  }
);

// API endpoints
export const authAPI = {
  // Login
  login: (credentials) => api.post('/auth/login', credentials),
  
  // Register
  register: (userData) => api.post('/auth/register', userData),
  
  // Forgot password - send code
  sendResetCode: (email) => api.post('/auth/forgot-password', { email }),
  
  // Reset password
  resetPassword: (data) => api.post('/auth/reset-password', data),
  
  // Verify email
  verifyEmail: (data) => api.post('/api/merchant/common/sendEmailCode', data),
  
  // Logout
  logout: () => api.post('/auth/logout'),
};

export const userAPI = {
  // Get user profile
  getProfile: () => api.get('/user/profile'),
  
  // Update profile
  updateProfile: (data) => api.put('/user/profile', data),
  
  // Update password
  updatePassword: (data) => api.put('/user/password', data),
  
  // Update transaction password
  updateTransactionPassword: (data) => api.put('/user/transaction-password', data),
};

export const dashboardAPI = {
  // Get balance
  getBalance: () => api.get('/dashboard/balance'),
  
  // Get transaction history
  getTransactions: (params) => api.get('/dashboard/transactions', { params }),
  
  // Get merchant info
  getMerchantInfo: () => api.get('/dashboard/merchant'),
};

export const withdrawalAPI = {
  // Single withdrawal
  createWithdrawal: (data) => api.post('/withdrawal/single', data),
  
  // Batch withdrawal
  createBatchWithdrawal: (data) => api.post('/withdrawal/batch', data),
  
  // Get withdrawal history
  getWithdrawalHistory: (params) => api.get('/withdrawal/history', { params }),
};

export const settingsAPI = {
  // Get settings
  getSettings: () => api.get('/settings'),
  
  // Update settings
  updateSettings: (data) => api.put('/settings', data),
  
  // Upload SSH key
  uploadSSHKey: (data) => api.post('/settings/ssh-key', data),
};

export default api;
