import axios from 'axios'

const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001/api'

// Debug: mostrar URL de la API
if (typeof window !== 'undefined') {
  console.log('API URL:', API_URL)
}

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

// Request interceptor to add auth token
api.interceptors.request.use((config) => {
  if (typeof window !== 'undefined') {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
  }
  return config
})

// Products
export const productsApi = {
  getAll: () => api.get('/products'),
  getBySlug: (slug: string) => api.get(`/products/${slug}`),
}

// Policies
export const policiesApi = {
  getAll: () => api.get('/policies'),
  getBySlug: (slug: string) => api.get(`/policies/${slug}`),
  getByType: (type: string) => api.get(`/policies/type/${type}`),
}

// Contact - uses local API route
export const contactApi = {
  submit: (data: {
    name: string
    email: string
    phone?: string
    company?: string
    subject?: string
    message: string
  }) => axios.post('/api/contact', data),
}

// Site Config
export const siteConfigApi = {
  getAll: () => api.get('/site-config'),
  get: (key: string) => api.get(`/site-config/${key}`),
}

// Testimonials
export const testimonialsApi = {
  getAll: () => api.get('/testimonials'),
}

// Auth
export const authApi = {
  login: (data: { email: string; password: string }) =>
    api.post('/auth/login', data),
  register: (data: { email: string; password: string; name: string }) =>
    api.post('/auth/register', data),
  me: () => api.get('/auth/me'),
}
