import { getToken } from './authApi';

const API_BASE_URL = window.__ENV__?.API_BASE || 'http://localhost:8000';

/**
 * Trigger a manual database backup (admin only)
 */
export async function triggerBackup() {
  const token = getToken();
  const response = await fetch(`${API_BASE_URL}/admin/backup`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json',
    },
  });

  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.detail || 'Failed to create backup');
  }

  return response.json();
}

/**
 * List all available backups (admin only)
 */
export async function listBackups() {
  const token = getToken();
  const response = await fetch(`${API_BASE_URL}/admin/backups`, {
    method: 'GET',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json',
    },
  });

  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.detail || 'Failed to list backups');
  }

  return response.json();
}

/**
 * Restore database from a backup (admin only)
 */
export async function restoreBackup(filename) {
  const token = getToken();
  const response = await fetch(`${API_BASE_URL}/admin/restore?filename=${encodeURIComponent(filename)}`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json',
    },
  });

  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.detail || 'Failed to restore backup');
  }

  return response.json();
}
