import axios, { AxiosInstance, AxiosError } from 'axios';

const API_BASE_URL = import.meta.env.VITE_API_URL || 'http://localhost:8000/api/v1';

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

// Request interceptor to add auth token
api.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

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

// Auth API
export const authAPI = {
  login: async (username: string, password: string) => {
    const response = await api.post('/auth/login', { username, password });
    return response.data;
  },
  
  register: async (data: {
    email: string;
    username: string;
    password: string;
    full_name?: string;
  }) => {
    const response = await api.post('/auth/register', data);
    return response.data;
  },
  
  getMe: async () => {
    const response = await api.get('/auth/me');
    return response.data;
  },
};

// API Keys API
export const apiKeysAPI = {
  getAll: async () => {
    const response = await api.get('/api-keys');
    return response.data;
  },
  
  create: async (name: string) => {
    const response = await api.post('/api-keys', { name });
    return response.data;
  },
  
  delete: async (id: number) => {
    const response = await api.delete(`/api-keys/${id}`);
    return response.data;
  },
  
  revoke: async (id: number) => {
    const response = await api.post(`/api-keys/${id}/revoke`);
    return response.data;
  },
  
  reactivate: async (id: number) => {
    const response = await api.post(`/api-keys/${id}/reactivate`);
    return response.data;
  },
};

// SMTP Config API
export const smtpAPI = {
  getAll: async () => {
    const response = await api.get('/smtp-configs');
    return response.data;
  },
  
  create: async (data: {
    name: string;
    host: string;
    port: number;
    username: string;
    password: string;
    use_tls?: boolean;
    is_default?: boolean;
  }) => {
    const response = await api.post('/smtp-configs', data);
    return response.data;
  },
  
  update: async (id: number, data: Partial<{
    name: string;
    host: string;
    port: number;
    username: string;
    password: string;
    use_tls: boolean;
    is_default: boolean;
  }>) => {
    const response = await api.put(`/smtp-configs/${id}`, data);
    return response.data;
  },
  
  delete: async (id: number) => {
    const response = await api.delete(`/smtp-configs/${id}`);
    return response.data;
  },
};

// Email API
export const emailAPI = {
  send: async (data: {
    to_email: string;
    subject: string;
    body: string;
    from_name?: string;
    is_html?: boolean;
  }) => {
    const response = await api.post('/emails/send', data);
    return response.data;
  },
  
  getLogs: async (limit: number = 50) => {
    const response = await api.get('/emails/logs', { params: { limit } });
    return response.data;
  },
};

// Dashboard API
export const dashboardAPI = {
  getStats: async () => {
    const response = await api.get('/dashboard/stats');
    return response.data;
  },
};

// Public API (for documentation)
export const publicAPI = {
  sendEmail: async (apiKey: string, data: {
    to_email: string;
    subject: string;
    body: string;
    from_email?: string;
    from_name?: string;
    is_html?: boolean;
  }) => {
    const response = await axios.post(`${API_BASE_URL}/public/send-email`, {
      api_key: apiKey,
      ...data,
    });
    return response.data;
  },
};

export default api;
