import axios from 'axios';

const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3002';

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

// Add auth token to requests
api.interceptors.request.use((config) => {
  const token = localStorage.getItem('token');
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
});

// Handle auth errors
api.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response?.status === 401) {
      localStorage.removeItem('token');
      localStorage.removeItem('user');
      window.location.href = '/login';
    }
    return Promise.reject(error);
  }
);

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

  login: async (email: string, password: string) => {
    const response = await api.post('/auth/login', { email, password });
    return response.data;
  },

  forgotPassword: async (email: string) => {
    const response = await api.post('/auth/forgot-password', { email });
    return response.data;
  },

  resetPassword: async (token: string, newPassword: string) => {
    const response = await api.post('/auth/reset-password', { token, newPassword });
    return response.data;
  },

  verifyEmail: async (token: string) => {
    const response = await api.post('/auth/verify-email', { token });
    return response.data;
  },

  resendVerification: async (email: string) => {
    const response = await api.post('/auth/resend-verification', { email });
    return response.data;
  },
};

// Monitor API
export const monitorAPI = {
  list: async () => {
    const response = await api.get('/monitors');
    return response.data;
  },

  get: async (id: string) => {
    const response = await api.get(`/monitors/${id}`);
    return response.data;
  },

  create: async (data: any) => {
    const response = await api.post('/monitors', data);
    return response.data;
  },

  update: async (id: string, data: any) => {
    const response = await api.put(`/monitors/${id}`, data);
    return response.data;
  },

  delete: async (id: string) => {
    const response = await api.delete(`/monitors/${id}`);
    return response.data;
  },

  check: async (id: string) => {
    const response = await api.post(`/monitors/${id}/check`);
    return response.data;
  },

  history: async (id: string, limit = 50) => {
    const response = await api.get(`/monitors/${id}/history`, {
      params: { limit },
    });
    return response.data;
  },

  snapshot: async (id: string, snapshotId: string) => {
    const response = await api.get(`/monitors/${id}/history/${snapshotId}`);
    return response.data;
  },

  exportAuditTrail: async (id: string, format: 'json' | 'csv' = 'json') => {
    const token = localStorage.getItem('token');
    const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3002';
    const url = `${API_URL}/api/monitors/${id}/export?format=${format}`;

    // Create a hidden link and trigger download
    const response = await fetch(url, {
      headers: {
        'Authorization': `Bearer ${token}`,
      },
    });

    if (!response.ok) {
      throw new Error('Export failed');
    }

    const blob = await response.blob();
    const filename = response.headers.get('Content-Disposition')?.split('filename="')[1]?.replace('"', '')
      || `export.${format}`;

    const a = document.createElement('a');
    a.href = URL.createObjectURL(blob);
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(a.href);
  },
};

// Settings API
export const settingsAPI = {
  get: async () => {
    const response = await api.get('/settings');
    return response.data;
  },

  changePassword: async (currentPassword: string, newPassword: string) => {
    const response = await api.post('/settings/change-password', {
      currentPassword,
      newPassword,
    });
    return response.data;
  },

  updateNotifications: async (data: {
    emailEnabled?: boolean;
    webhookUrl?: string | null;
    webhookEnabled?: boolean;
    slackWebhookUrl?: string | null;
    slackEnabled?: boolean;
  }) => {
    const response = await api.put('/settings/notifications', data);
    return response.data;
  },

  deleteAccount: async (password: string) => {
    const response = await api.delete('/settings/account', {
      data: { password },
    });
    return response.data;
  },
};
