import { buildApiUrl, toUserFacingApiError } from './apiBase'

async function request(path, token, { method = 'GET', body } = {}) {
  const hasBody = body !== undefined
  const response = await fetch(buildApiUrl(path), {
    method,
    headers: {
      Authorization: `Bearer ${token}`,
      ...(hasBody ? { 'Content-Type': 'application/json' } : {}),
    },
    body: hasBody ? JSON.stringify(body) : undefined,
  })

  const data = await response.json().catch(() => ({}))

  if (!response.ok) {
    throw new Error(toUserFacingApiError(data, '관리자 데이터를 불러오지 못했습니다.'))
  }

  return data
}

export async function fetchAdminOverview(token) {
  return request('/api/admin/overview', token)
}

export async function fetchAdminUserDetail(token, userId) {
  return request(`/api/admin/users/${userId}/detail`, token)
}

export async function updateAdminUserStatus(token, userId, disabled) {
  return request(`/api/admin/users/${userId}/status`, token, {
    method: 'PUT',
    body: { disabled },
  })
}

export async function revokeAdminUserSessions(token, userId) {
  return request(`/api/admin/users/${userId}/revoke-sessions`, token, {
    method: 'POST',
  })
}

export async function deleteAdminUser(token, userId) {
  return request(`/api/admin/users/${userId}`, token, {
    method: 'DELETE',
  })
}
