import axios from 'axios';


const API_URL = 'http://localhost:3000';

const api = axios.create({
  baseURL: API_URL,
  // withCredentials: true,
});

// Add authorization header to all requests
api.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`;  // Make sure this matches your backend expectation
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

export const getSharedDocuments = (userId) => {
  return api.get(`/documents/shared/${userId}`);
};


const getToken = () => localStorage.getItem('token');
export const downloadDocument = async (key) => {
  try {
    const response = await api.get(`/documents/download/${encodeURIComponent(key)}`, {
      responseType: 'blob',
      headers: {
        'Accept': 'application/octet-stream',
      }
    });

    // Create blob URL and trigger download
    const blob = new Blob([response.data]);
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    
    // Extract filename from key
    const fileName = key.split('/').pop();
    link.download = fileName;
    
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
    
    return response;
  } catch (error) {
    console.error('Download error:', error);
    throw error;
  }
};


export const createUser = (userData) => {
  return api.post('/admin/users', {
    name: userData.name,
    email: userData.email,
    password: userData.password,
    isAdmin: userData.isAdmin  
  });
};
export const login = (username, password) => api.post('/auth/login', { username, password });
export const shareDocument = (documentId, userIds) => api.post(`/admin/documents/${documentId}/share`, { userIds });
export const updateDocumentStatus = (documentId, status) => api.put(`/admin/documents/${documentId}/status`, { status });

export const uploadDocument = async (formData) => {
  try {
    // Debug log
    console.log('Sending to server:', {
      title: formData.get('title'),
      sharedWithId: formData.get('sharedWithId'),
      uploadedById: formData.get('uploadedById')
    });

    const response = await api.post('/admin/documents', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });
    return response.data;
  } catch (error) {
    console.error('API Error:', error.response?.data);
    throw error;
  }
};
export const getUserInfo = () => api.get('/auth/user-info');


export const getAllDocuments = () => api.get('/admin/documents');
// export const getSharedDocuments = (userId) => api.get(`/documents/shared/${userId}`);
export const getAllUsers = () => api.get('/admin/users');

export default api;
