import axios from 'axios'

// Use relative path - works with both Vite dev proxy and IIS production proxy
const baseURL = import.meta.env.BASE_URL + 'api/data-entry'

const api = axios.create({
  baseURL,
  headers: { 'Content-Type': 'application/json' }
})

// Request interceptor for auth token and company header
api.interceptors.request.use((config) => {
  const token = localStorage.getItem('access_token')
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }

  // Add selected company header if available
  const user = JSON.parse(localStorage.getItem('user') || '{}')
  const username = user.username

  // Try to get selected company from saved company object first
  let selectedCompanyId = null
  if (username) {
    const savedCompany = localStorage.getItem(`selected_company_${username}`)
    if (savedCompany) {
      try {
        const company = JSON.parse(savedCompany)
        selectedCompanyId = company.id_firma
      } catch (e) {
        console.error('Failed to parse saved company:', e)
      }
    }
  }

  // Fallback to first company in user.companies if no saved company
  if (!selectedCompanyId) {
    selectedCompanyId = user.companies?.[0]
  }

  if (selectedCompanyId) {
    config.headers['X-Selected-Company'] = selectedCompanyId
  }

  // For FormData uploads, remove Content-Type header to let browser set it with boundary
  if (config.data instanceof FormData) {
    delete config.headers['Content-Type']
  }

  return config
})

// Response interceptor for error handling
api.interceptors.response.use(
  (response) => {
    console.log('✅ API Response:', response.config.url, response.status)
    return response
  },
  (error) => {
    console.error('❌ API Error:', {
      url: error.config?.url,
      method: error.config?.method,
      code: error.code,
      message: error.message
    })
    if (error.response?.status === 401) {
      // Token expired or invalid - redirect to login
      localStorage.removeItem('access_token')
      localStorage.removeItem('refresh_token')
      localStorage.removeItem('user')
      window.location.href = import.meta.env.BASE_URL + 'login'
    }
    return Promise.reject(error)
  }
)

export default api
