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

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

export function adminCreateUser(body) {
  return request('/api/admin/users', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
  })
}

export function adminDeactivateUser(id) {
  return request(`/api/admin/users/${id}/status`, {
    method: 'PATCH',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ is_active: false }),
  })
}

export function adminReactivateUser(id) {
  return request(`/api/admin/users/${id}/status`, {
    method: 'PATCH',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ 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 request(`/api/admin/users/${id}/quota`, {
    method: 'PATCH',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ limit_bytes: limitBytes }),
  })
}

export function adminUpdateAiConfig(id, provider, model) {
  return request(`/api/admin/users/${id}/ai-config`, {
    method: 'PATCH',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ ai_provider: provider, ai_model: model }),
  })
}

export function adminDeleteUser(id, adminPassword) {
  return request(`/api/admin/users/${id}`, {
    method: 'DELETE',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ admin_password: adminPassword }),
  })
}

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

export function saveAiConfig(body) {
  return request('/api/admin/ai-config', {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(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 = new URLSearchParams()
  if (start) params.set('start', start)
  if (end) params.set('end', end)
  if (user_handle) params.set('user_handle', user_handle)
  if (event_type) params.set('event_type', event_type)
  params.set('page', page)
  params.set('per_page', per_page)
  return request(`/api/admin/audit-log?${params}`)
}

// Unlike window.location.href, fetchWithRetry sends the Authorization Bearer header so
// the endpoint can authenticate. Must NOT call res.json() — CSV is text/csv.
export async function adminExportAuditLogCsv(params = {}) {
  const searchParams = new URLSearchParams({ format: 'csv' })
  if (params.start) searchParams.set('start', params.start)
  if (params.end) searchParams.set('end', params.end)
  if (params.user_handle) searchParams.set('user_handle', params.user_handle)
  if (params.event_type) searchParams.set('event_type', params.event_type)

  const res = await fetchWithRetry(`/api/admin/audit-log/export?${searchParams}`)
  if (!res.ok) throw new Error(`Export failed: ${res.status}`)

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

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

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

// Uses fetchWithRetry() to send the Authorization Bearer header (D-17, T-06.2-04-03).
export async function adminDownloadDailyExport(date) {
  const res = await fetchWithRetry(`/api/admin/audit-log/daily-exports/${date}`)
  if (!res.ok) throw new Error(`Download failed: ${res.status}`)

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