/**
 * API Client
 *
 * Axios instance with authentication interceptors.
 */

import axios, { AxiosError, InternalAxiosRequestConfig } from 'axios';
import { API_MOBILE_URL } from '../config/api';
import { getAuthToken, clearAllAuthData } from '../services/storage';

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

// Request interceptor to add auth token
apiClient.interceptors.request.use(
  async (config: InternalAxiosRequestConfig) => {
    const token = await getAuthToken();
    if (token) {
      config.headers.Authorization = `Token ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// Response interceptor for error handling
apiClient.interceptors.response.use(
  (response) => response,
  async (error: AxiosError) => {
    if (error.response?.status === 401) {
      // Clear auth data on unauthorized
      await clearAllAuthData();
    }
    return Promise.reject(error);
  }
);

export default apiClient;
