import axios from 'axios';

const BASE = window.__BASE_PATH__ || '';

const api = axios.create({
  baseURL: BASE,
  withCredentials: true,
  headers: { 'Content-Type': 'application/json' },
});

let csrfToken = '';

export async function fetchCsrf() {
  const res = await api.get('/api/csrf');
  csrfToken = res.data.csrfToken;
  return csrfToken;
}

function withCsrf() {
  return { headers: { 'X-CSRF-Token': csrfToken } };
}

// Auth
export async function login(username, password) {
  if (!csrfToken) await fetchCsrf();
  return api.post('/api/login', { username, password }, withCsrf());
}
export async function logout() { return api.post('/api/logout', {}, withCsrf()); }
export async function getMe() { return api.get('/api/me'); }
export async function changePassword(currentPassword, newPassword) {
  if (!csrfToken) await fetchCsrf();
  return api.post('/api/change-password', { currentPassword, newPassword }, withCsrf());
}

// Files
export async function getFiles(folderId = null) {
  const params = folderId !== null ? { folder_id: folderId } : {};
  return api.get('/api/files', { params });
}
export async function initUpload(fileName, mimeType, sizeBytes) {
  if (!csrfToken) await fetchCsrf();
  return api.post('/api/files/init-upload', { fileName, mimeType, sizeBytes }, withCsrf());
}
export async function completeUpload(objectKey, originalName, displayName, mimeType, folderId = null) {
  return api.post('/api/files/complete-upload', { objectKey, originalName, displayName, mimeType, folderId }, withCsrf());
}
export async function renameFile(id, displayName) {
  if (!csrfToken) await fetchCsrf();
  return api.post(`/api/files/${id}/rename`, { displayName }, withCsrf());
}
export async function deleteFile(id, permanent = false) {
  if (!csrfToken) await fetchCsrf();
  return api.delete(`/api/files/${id}${permanent ? '?permanent=1' : ''}`, withCsrf());
}
export async function restoreFile(id) {
  if (!csrfToken) await fetchCsrf();
  return api.post(`/api/files/${id}/restore`, {}, withCsrf());
}
export async function shareFile(id, enabled) {
  if (!csrfToken) await fetchCsrf();
  return api.post(`/api/files/${id}/share`, { enabled }, withCsrf());
}
export async function getDownloadUrl(id) { return api.get(`/api/files/${id}/download-url`); }
export async function getPreviewUrl(id) { return api.get(`/api/files/${id}/preview-url`); }

// Folders
export async function createFolder(name, parentId = null) {
  if (!csrfToken) await fetchCsrf();
  return api.post('/api/folders', { name, parentId }, withCsrf());
}
export async function renameFolder(id, name) {
  if (!csrfToken) await fetchCsrf();
  return api.post(`/api/folders/${id}/rename`, { name }, withCsrf());
}
export async function deleteFolder(id, permanent = false) {
  if (!csrfToken) await fetchCsrf();
  return api.delete(`/api/folders/${id}${permanent ? '?permanent=1' : ''}`, withCsrf());
}
export async function restoreFolder(id) {
  if (!csrfToken) await fetchCsrf();
  return api.post(`/api/folders/${id}/restore`, {}, withCsrf());
}
export async function shareFolder(id, enabled) {
  if (!csrfToken) await fetchCsrf();
  return api.post(`/api/folders/${id}/share`, { enabled }, withCsrf());
}

// Move
export async function moveFile(id, folderId) {
  if (!csrfToken) await fetchCsrf();
  return api.post(`/api/files/${id}/move`, { folderId }, withCsrf());
}
export async function moveFolder(id, parentId) {
  if (!csrfToken) await fetchCsrf();
  return api.post(`/api/folders/${id}/move`, { parentId }, withCsrf());
}

// Trash
export async function getTrash() { return api.get('/api/trash'); }
export async function getTrashCount() { return api.get('/api/trash/count'); }
export async function emptyTrash() {
  if (!csrfToken) await fetchCsrf();
  return api.post('/api/trash/empty', {}, withCsrf());
}

// Usage
export async function getUsage() { return api.get('/api/usage'); }

// Upload to R2
export function uploadToR2(url, file, contentType, onProgress) {
  return axios.put(url, file, {
    headers: { 'Content-Type': contentType },
    onUploadProgress: (e) => {
      if (onProgress && e.total) onProgress(Math.round((e.loaded / e.total) * 100));
    },
  });
}

export default api;
