import api from './api';

/**
 * Get audit logs with pagination and filters
 */
export const getAuditLogs = async (params = {}) => {
  try {
    const response = await api.get('/audit-logs', { params });
    return {
      success: true,
      data: response.data.data || response.data,
      pagination: response.data.pagination || {}
    };
  } catch (error) {
    return {
      success: false,
      message: error.response?.data?.message || 'Fehler beim Laden der Audit-Logs'
    };
  }
};

/**
 * Get aggregate statistics (counts by action, admin, resource, daily activity)
 */
export const getAuditStats = async (days = 30) => {
  try {
    const response = await api.get('/audit-logs/stats', { params: { days } });
    return { success: true, data: response.data.data };
  } catch (error) {
    return {
      success: false,
      message: error.response?.data?.message || 'Fehler beim Laden der Statistiken'
    };
  }
};

/**
 * Download audit logs as CSV (applies same filters as getAuditLogs)
 */
export const exportAuditLogs = async (params = {}) => {
  try {
    const response = await api.get('/audit-logs/export', {
      params,
      responseType: 'blob'
    });
    const filename = `audit-logs_${new Date().toISOString().slice(0, 10)}.csv`;
    const url = window.URL.createObjectURL(new Blob([response.data], { type: 'text/csv;charset=utf-8;' }));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', filename);
    document.body.appendChild(link);
    link.click();
    link.remove();
    window.URL.revokeObjectURL(url);
    return { success: true };
  } catch (error) {
    return {
      success: false,
      message: error.response?.data?.message || 'Fehler beim Exportieren der Audit-Logs'
    };
  }
};

/**
 * Get audit logs for a specific resource
 */
export const getResourceAuditLogs = async (resource, resourceId) => {
  try {
    const response = await api.get(`/audit-logs/${resource}/${resourceId}`);
    return { success: true, data: response.data.data || response.data };
  } catch (error) {
    return {
      success: false,
      message: error.response?.data?.message || 'Fehler beim Laden der Resource-Audit-Logs'
    };
  }
};

/**
 * Get admin activity
 */
export const getAdminActivity = async (adminId) => {
  try {
    const response = await api.get(`/audit-logs/admin/${adminId}`);
    return { success: true, data: response.data.data || response.data };
  } catch (error) {
    return {
      success: false,
      message: error.response?.data?.message || 'Fehler beim Laden der Admin-Aktivität'
    };
  }
};

