import axios from 'axios';


const api = axios.create({
  baseURL: 'http://localhost:8000', // Your FastAPI URL
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
  },
  withCredentials: true, // If you need to send cookies
});

// Add request interceptor to include token
api.interceptors.request.use((config) => {
  const token = localStorage.getItem('token');
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
});

// Add response interceptor to handle 401 errors
api.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response?.status === 401) {
      // Token expired or invalid - force logout
      localStorage.removeItem('token');
      window.location.href = '/login';
    }
    return Promise.reject(error);
  }
);

export default api;

// Auth services
export const authService = {
  register: (data: { username: string; password: string; email: string }) =>
    api.post('/auth/register', data),
    
  login: (email: string, password: string) => {
    return api.post('/auth/login', {
      email,  // Changed from username
      password
    }, {
      headers: {
        'Content-Type': 'application/json',
      }
    });
  },
};

// Chart services
export const chartService = {
  AskQuestion: (formData: FormData) => 
    api.post('/charts/ask', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
        'accept': 'application/json',
      },
    }),
  analyzeChart: (formData: FormData) => 
    api.post('/charts/analyze', formData, {
      headers: {
        'accept': 'application/json',
        'Content-Type': 'multipart/form-data',
      },
    }),
};

// General services
export const appService = {
  getRoot: () => api.get('/'),
};