/**
 * API Service
 * Centralized API communication service
 */

import axios from 'axios';
import AsyncStorage from '@react-native-async-storage/async-storage';

// Update this with your actual API base URL
const API_BASE_URL = 'https://your-domain.com/api/v1';

// Create axios instance
const apiClient = axios.create({
  baseURL: API_BASE_URL,
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// Request interceptor - Add auth token
apiClient.interceptors.request.use(
  async (config) => {
    const token = await AsyncStorage.getItem('auth_token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// Response interceptor - Handle errors
apiClient.interceptors.response.use(
  (response) => {
    return response.data;
  },
  async (error) => {
    if (error.response) {
      // Handle 401 - Unauthorized
      if (error.response.status === 401) {
        // Clear token and redirect to login
        await AsyncStorage.removeItem('auth_token');
        await AsyncStorage.removeItem('user_data');
        // You can dispatch a logout action here if using Redux
      }
      
      return Promise.reject({
        message: error.response.data?.message || 'An error occurred',
        status: error.response.status,
        data: error.response.data,
      });
    }
    
    return Promise.reject({
      message: 'Network error. Please check your connection.',
      status: 0,
    });
  }
);

export const ApiService = {
  // Generic GET request
  get: async (endpoint, params = {}) => {
    try {
      return await apiClient.get(endpoint, { params });
    } catch (error) {
      throw error;
    }
  },

  // Generic POST request
  post: async (endpoint, data = {}) => {
    try {
      return await apiClient.post(endpoint, data);
    } catch (error) {
      throw error;
    }
  },

  // Generic PUT request
  put: async (endpoint, data = {}) => {
    try {
      return await apiClient.put(endpoint, data);
    } catch (error) {
      throw error;
    }
  },

  // Generic DELETE request
  delete: async (endpoint) => {
    try {
      return await apiClient.delete(endpoint);
    } catch (error) {
      throw error;
    }
  },
};

export default ApiService;
