import axios from 'axios';
import { useAuthStore } from '@/lib/store/auth';

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

// Attach token automatically
api.interceptors.request.use((config) => {
  const token = useAuthStore.getState().token;
  if (token) config.headers.Authorization = `Bearer ${token}`;
  return config;
});

// Handle 401 globally
api.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response?.status === 401) {
      useAuthStore.getState().logout();
    }
    return Promise.reject(error);
  }
);

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

// Plans
export const plansApi = {
  list: () => api.get('/plans'),
  get: (slug: string) => api.get(`/plans/${slug}`),
  review: (id: string, data: { rating: number; title?: string; body?: string }) =>
    api.post(`/plans/${id}/review`, data)
};

// AI Planner
export const aiApi = {
  generatePlan: (data: object) => api.post('/ai/generate-plan', data),
  getSessions: () => api.get('/ai/sessions'),
  getSession: (id: string) => api.get(`/ai/sessions/${id}`),
  getStatus: () => api.get('/ai/status')
};

// Tracker
export const trackerApi = {
  log: (data: object) => api.post('/tracker/log', data),
  getLogs: (from?: string, to?: string) =>
    api.get('/tracker/logs', { params: { from, to } }),
  getSummary: () => api.get('/tracker/summary')
};

// Payments
export const paymentsApi = {
  checkout: (planId: string, couponCode?: string) =>
    api.post('/payments/checkout', { planId, couponCode }),
  subscribe: (tier: string) => api.post('/payments/subscribe', { tier }),
  portal: () => api.post('/payments/portal')
};

// User
export const userApi = {
  dashboard: () => api.get('/user/dashboard'),
  updateProfile: (data: object) => api.patch('/user/profile', data),
  toggleWishlist: (productId: string) => api.post(`/user/wishlist/${productId}`)
};

// Leads
export const leadsApi = {
  subscribe: (email: string, name?: string, source?: string) =>
    api.post('/leads', { email, name, source })
};

// Products
export const productsApi = {
  list: (category?: string, tag?: string) =>
    api.get('/products', { params: { category, tag } }),
  trackClick: (id: string) => api.post(`/products/${id}/click`)
};

// Blog
export const blogApi = {
  list: (params?: { category?: string; tag?: string; page?: number }) =>
    api.get('/blog', { params }),
  get: (slug: string) => api.get(`/blog/${slug}`)
};
