import { request, fetchWithRetry, jsonRequest } from './utils.js'

function withPresentParams(initial = {}, params = {}) {
  const searchParams = new URLSearchParams(initial)
  Object.entries(params).forEach(([key, value]) => {
    if (value) searchParams.set(key, value)
  })
  return searchParams
}

async function downloadCsv(url, filename, errorPrefix) {
  const res = await fetchWithRetry(url)
  if (!res.ok) throw new Error(`${errorPrefix}: ${res.status}`)

  const blob = new Blob([await res.text()], { type: 'text/csv' })
  const objectUrl = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = objectUrl
  a.download = filename
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  setTimeout(() => URL.revokeObjectURL(objectUrl), 1000)
}

export function adminListUsers() {
  return request('/api/admin/users')
}

export function adminCreateUser(body) {
  return jsonRequest('/api/admin/users', 'POST', body)
}

export function adminDeactivateUser(id) {
  return jsonRequest(`/api/admin/users/${id}/status`, 'PATCH', { is_active: false })
}

export function adminReactivateUser(id) {
  return jsonRequest(`/api/admin/users/${id}/status`, 'PATCH', { is_active: true })
}

export function adminResetUserPassword(id) {
  return request(`/api/admin/users/${id}/password-reset`, { method: 'POST' })
}

export function adminGetUserQuota(id) {
  return request(`/api/admin/users/${id}/quota`)
}

export function adminUpdateQuota(id, limitBytes) {
  return jsonRequest(`/api/admin/users/${id}/quota`, 'PATCH', { limit_bytes: limitBytes })
}

export function adminUpdateAiConfig(id, provider, model) {
  return jsonRequest(`/api/admin/users/${id}/ai-config`, 'PATCH', {
    ai_provider: provider,
    ai_model: model,
  })
}

export function adminDeleteUser(id, adminPassword) {
  return jsonRequest(`/api/admin/users/${id}`, 'DELETE', { admin_password: adminPassword })
}

export function getAiConfig() {
  return request('/api/admin/ai-config', { method: 'GET' })
}

export function saveAiConfig(body) {
  return jsonRequest('/api/admin/ai-config', 'PUT', body)
}

export function testAiConnection(providerId) {
  return request(
    '/api/admin/ai-config/test-connection?provider_id=' + encodeURIComponent(providerId),
    { method: 'GET' }
  )
}

export function getAiModels(providerId) {
  return request(
    '/api/admin/ai-config/models?provider_id=' + encodeURIComponent(providerId),
    { method: 'GET' }
  )
}

export function adminListAuditLog({ start, end, user_handle, event_type, page = 1, per_page = 50 } = {}) {
  const params = withPresentParams({}, { start, end, user_handle, event_type })
  params.set('page', page)
  params.set('per_page', per_page)
  return request(`/api/admin/audit-log?${params}`)
}

export async function adminExportAuditLogCsv(params = {}) {
  const searchParams = withPresentParams(
    { format: 'csv' },
    {
      start: params.start,
      end: params.end,
      user_handle: params.user_handle,
      event_type: params.event_type,
    }
  )
  return downloadCsv(`/api/admin/audit-log/export?${searchParams}`, 'audit-export.csv', 'Export failed')
}

export function adminListDailyExports() {
  return request('/api/admin/audit-log/daily-exports')
}

export async function getAdminOverview() {
  return request('/api/admin/overview')
}

export async function adminDownloadDailyExport(date) {
  return downloadCsv(`/api/admin/audit-log/daily-exports/${date}`, `audit-${date}.csv`, 'Download failed')
}
