import api from './api';

export const getUsers = async (params = {}) => {
  try {
    const response = await api.get('/users', { 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 Benutzer'
    };
  }
};

export const getUserById = async (id) => {
  try {
    const response = await api.get(`/users/${id}`);
    return { success: true, data: response.data.data || response.data };
  } catch (error) {
    return {
      success: false,
      message: error.response?.data?.message || 'Fehler beim Laden des Benutzers'
    };
  }
};

export const createUser = async (userData) => {
  try {
    const response = await api.post('/users', userData);
    return {
      success: true,
      data: response.data.data || response.data,
      warning: response.data.warning || null
    };
  } catch (error) {
    return {
      success: false,
      message: error.response?.data?.message || 'Fehler beim Erstellen des Benutzers'
    };
  }
};

export const updateUser = async (id, userData) => {
  try {
    const response = await api.put(`/users/${id}`, userData);
    return {
      success: true,
      data: response.data.data || response.data,
      warning: response.data.warning || null
    };
  } catch (error) {
    return {
      success: false,
      message: error.response?.data?.message || 'Fehler beim Aktualisieren des Benutzers'
    };
  }
};

export const deleteUser = async (id) => {
  try {
    const response = await api.delete(`/users/${id}`);
    return { success: true, message: response.data.message || 'Benutzer erfolgreich gelöscht' };
  } catch (error) {
    return {
      success: false,
      message: error.response?.data?.message || 'Fehler beim Löschen des Benutzers'
    };
  }
};

export const getPublicUsers = async (params = {}) => {
  try {
    const response = await api.get('/public/users', { 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 Benutzer'
    };
  }
};

export const updateAvailability = async (id, available) => {
  try {
    const response = await api.put(`/users/${id}/availability`, { available });
    return { success: true, data: response.data.data || response.data };
  } catch (error) {
    return {
      success: false,
      message: error.response?.data?.message || 'Fehler beim Aktualisieren der Verfügbarkeit'
    };
  }
};

export const updateGPS = async (id, lat, lng) => {
  try {
    const response = await api.put(`/users/${id}/gps`, { lat, lng });
    return { success: true, data: response.data.data || response.data };
  } catch (error) {
    return {
      success: false,
      message: error.response?.data?.message || 'Fehler beim Aktualisieren der GPS-Koordinaten'
    };
  }
};

export const exportUsers = async (format = 'csv') => {
  try {
    const today = new Date().toISOString().slice(0, 10);
    const filename = `nachsuchenfuehrer_export_${today}.${format}`;

    const response = await api.get(`/users/export?format=${format}`, {
      responseType: 'blob'
    });

    const mimeType = format === 'csv' ? 'text/csv;charset=utf-8;' : 'application/json';
    const url = window.URL.createObjectURL(new Blob([response.data], { type: mimeType }));
    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'
    };
  }
};

export const importUsers = async (jsonData, overwrite = false) => {
  try {
    const response = await api.post(
      `/users/import${overwrite ? '?overwrite=true' : ''}`,
      jsonData
    );
    return { success: true, data: response.data };
  } catch (error) {
    return {
      success: false,
      message: error.response?.data?.message || 'Fehler beim Importieren'
    };
  }
};

export const getDeletedUsers = async () => {
  try {
    const response = await api.get('/users/deleted');
    return { success: true, data: response.data.data || response.data };
  } catch (error) {
    return {
      success: false,
      message: error.response?.data?.message || 'Fehler beim Laden gelöschter Benutzer'
    };
  }
};

export const restoreUser = async (id) => {
  try {
    const response = await api.post(`/users/${id}/restore`);
    return { success: true, data: response.data.data || response.data };
  } catch (error) {
    return {
      success: false,
      message: error.response?.data?.message || 'Fehler beim Wiederherstellen des Benutzers'
    };
  }
};

export const bulkUpdateUsers = async (ids, updates) => {
  try {
    const response = await api.patch('/users/bulk', { ids, updates });
    return { success: true, data: response.data };
  } catch (error) {
    return {
      success: false,
      message: error.response?.data?.message || 'Fehler beim Bulk-Update'
    };
  }
};

export const bulkDeleteUsers = async (ids) => {
  try {
    const response = await api.delete('/users/bulk', { data: { ids } });
    return { success: true, data: response.data };
  } catch (error) {
    return {
      success: false,
      message: error.response?.data?.message || 'Fehler beim Bulk-Delete'
    };
  }
};

export const uploadUserPhoto = async (id, photoDataUrl) => {
  try {
    const response = await api.post(`/users/${id}/photo`, { photo: photoDataUrl });
    return { success: true, data: response.data };
  } catch (error) {
    return {
      success: false,
      message: error.response?.data?.message || 'Fehler beim Foto-Upload'
    };
  }
};

export const deleteUserPhoto = async (id) => {
  try {
    await api.delete(`/users/${id}/photo`);
    return { success: true };
  } catch (error) {
    return {
      success: false,
      message: error.response?.data?.message || 'Fehler beim Löschen des Fotos'
    };
  }
};
