import axios from 'axios';

const api = axios.create({
  baseURL: process.env.NEXT_PUBLIC_API_URL || '/api/v1',
  withCredentials: true, // Send cookies with requests
});

// Request interceptor - set Content-Type based on data type
api.interceptors.request.use((config) => {
  // Let axios auto-detect Content-Type for FormData
  // Only set application/json for non-FormData requests
  if (!(config.data instanceof FormData)) {
    config.headers['Content-Type'] = 'application/json';
  }
  return config;
});

// Response interceptor for error handling
api.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response?.status === 401) {
      localStorage.removeItem('token');
      window.location.href = '/login';
    }
    return Promise.reject(error);
  }
);

// Jobs API
export const jobsApi = {
  create: (data: any) => api.post('/jobs/', data),
  get: (id: string) => api.get(`/jobs/${id}`),
  list: (params?: any) => api.get('/jobs/', { params }),
  cancel: (id: string) => api.post(`/jobs/${id}/cancel`),
};

// Assets API
export const assetsApi = {
  upload: (file: File, projectId?: string, isTemporary: boolean = false, overwrite: boolean = false) => {
    const formData = new FormData();
    formData.append('file', file);
    if (projectId) formData.append('project_id', projectId);
    formData.append('is_temporary', String(isTemporary));
    formData.append('overwrite', String(overwrite));
    return api.post('/assets/upload', formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
    });
  },
  get: (id: string) => api.get(`/assets/${id}`),
  list: (params?: any) => api.get('/assets/', { params }),
  download: (id: string) => api.get(`/assets/${id}/download`, { responseType: 'blob' }),
  delete: (id: string) => api.delete(`/assets/${id}`),
};

// Modules API
export const modulesApi = {
  // Image
  generateImage: (data: any) => api.post('/modules/image/generate', data),
  upscaleImage: (data: any) => api.post('/modules/image/upscale', data),
  removeBackground: (data: any) => api.post('/modules/image/remove-background', data),

  // Video
  generateVideo: (data: any) => api.post('/modules/video/generate', data),
  upscaleVideo: (data: any) => api.post('/modules/video/upscale', data),
  extractFrame: (data: { asset_id: string; timestamp: number }) => api.post('/modules/video/extract-frame', data),
  processSubtitles: (data: any) => api.post('/modules/video/subtitles', data),

  // Audio
  voiceToText: (data: any) => api.post('/modules/audio/voice-to-text', data),
  textToSpeech: (data: any) => api.post('/modules/audio/text-to-speech', data),
  speechToSpeech: (data: any) => api.post('/modules/audio/speech-to-speech', data),
  generateSoundEffect: (data: any) => api.post('/modules/audio/sound-effects', data),
  getSoundEffectFormats: () => api.get('/modules/audio/sound-effects/formats'),
  getVoices: () => api.get('/modules/voices'),

  // Text
  generateAltText: (data: any) => api.post('/modules/text/alt-text', data),
  enhancePrompt: (data: any) => api.post('/modules/text/enhance-prompt', data),

  // Mermaid
  generateMermaid: (data: any) => api.post('/modules/text/mermaid/generate', data),
  renderMermaid: (data: any) => api.post('/modules/text/mermaid/render', data),
  getMermaidTemplates: () => api.get('/modules/text/mermaid/templates'),
  getMermaidTemplate: (type: string) => api.get(`/modules/text/mermaid/templates/${type}`),

  // Markdown
  convertMarkdown: (data: any) => api.post('/modules/text/markdown/convert', data),
  generateMarkdown: (data: any) => api.post('/modules/text/markdown/generate', data),

  // Utils
  getModels: (provider: string) => api.get(`/modules/models/${provider}`),
  getImageProviders: () => api.get('/modules/image/providers'),
  getVideoProviders: () => api.get('/modules/video/providers'),
};

// Capabilities API
export const capabilitiesApi = {
  getImageProviders: () => api.get('/modules/capabilities/image'),
  getVideoProviders: () => api.get('/modules/capabilities/video'),
  getImageProvider: (providerId: string) => api.get(`/modules/capabilities/image/${providerId}`),
  getVideoProvider: (providerId: string) => api.get(`/modules/capabilities/video/${providerId}`),
};

// Users API
export const usersApi = {
  me: () => api.get('/users/me'),
  updateProfile: (data: any) => api.put('/users/me', data),
  getUsage: () => api.get('/users/me/usage'),
};

// Auth API
export const authApi = {
  signup: (data: { email: string; password: string; display_name: string }) =>
    api.post('/auth/signup', data),
  login: (data: { email: string; password: string }) =>
    api.post('/auth/login', data),
  logout: () => api.post('/auth/logout'),
  me: () => api.get('/auth/me'),
  updateProfile: (data: { display_name?: string; avatar_url?: string }) =>
    api.patch('/auth/me', data),
  changePassword: (data: { current_password: string; new_password: string }) =>
    api.post('/auth/me/change-password', data),
  verify: () => api.get('/auth/verify'),
};

export default api;
