import axios from 'axios'

// Get API base URL from environment or default
const API_BASE_URL = import.meta.env.VITE_API_URL || 'http://localhost:8001'

// Create axios instance with default config
const api = axios.create({
  baseURL: API_BASE_URL,
  headers: {
    'Content-Type': 'application/json',
  },
})

// Auto-attach JWT token from localStorage
api.interceptors.request.use((config) => {
  const token = localStorage.getItem('token')
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
}, (error) => {
  return Promise.reject(error)
})

// Handle 401 errors by clearing token and redirecting
api.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response?.status === 401) {
      localStorage.removeItem('token')
      localStorage.removeItem('user_id')
      window.location.href = '/login'
    }
    return Promise.reject(error)
  }
)

// Auth endpoints
export const authAPI = {
  register: (username, email, password, displayName) =>
    api.post('/auth/register', { username, email, password, display_name: displayName }),
  login: (emailOrUsername, password) =>
    api.post('/auth/login', { email_or_username: emailOrUsername, password }),
  getCurrentUser: () =>
    api.get('/auth/me'),
}

// Profile endpoints
export const profileAPI = {
  getMyProfile: () =>
    api.get('/profiles/me'),
  getProfile: (userId) =>
    api.get(`/profiles/${userId}`),
  createOrUpdateProfile: (data) =>
    api.post('/profiles/', data),
  discoverProfiles: () =>
    api.get('/profiles/discover/list'),
}

// Photo endpoints
export const photoAPI = {
  uploadPhoto: (file) => {
    const formData = new FormData()
    formData.append('file', file)
    return api.post('/photos/upload', formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
    })
  },
  getPhotoInfo: (photoId) =>
    api.get(`/photos/${photoId}`),
  deletePhoto: (photoId) =>
    api.delete(`/photos/${photoId}`),
}

// Like endpoints
export const likeAPI = {
  likeUser: (userId) =>
    api.post(`/likes/${userId}`),
  unlikeUser: (userId) =>
    api.delete(`/likes/${userId}`),
  getMatches: () =>
    api.get('/likes/matches/list'),
  getLikesReceived: () =>
    api.get('/likes/received/list'),
  getLikedProfiles: () =>
    api.get('/likes/sent/list'),
  acknowledgeLikes: () =>
    api.post('/likes/received/acknowledge'),
}

// Chat endpoints
export const chatAPI = {
  getConversations: () =>
    api.get('/chat/conversations'),
  getMessages: (conversationId, limit = 50) =>
    api.get(`/chat/conversations/${conversationId}/messages`, { params: { limit } }),
  sendMessage: (conversationId, content) =>
    api.post(`/chat/conversations/${conversationId}/messages`, { content }),
  markAsRead: (conversationId) =>
    api.post(`/chat/conversations/${conversationId}/mark-read`),
}

export { API_BASE_URL }
export default api
