import { apiRequest, getRuntimeApiBaseUrl } from './api.js'
import { buildBearerHeaders } from '../utils/authSessionStorage.js'

export function login(payload) {
  return apiRequest('/auth/login', {
    auth: false,
    handleUnauthorized: false,
    method: 'POST',
    body: JSON.stringify(payload)
  })
}

export function fetchCurrentAuthUser() {
  return apiRequest('/auth/me')
}

export function revokeCurrentAuthSession(payload) {
  return apiRequest('/auth/logout', {
    method: 'POST',
    handleUnauthorized: false,
    body: JSON.stringify(payload || {})
  })
}

export function finishSession(sessionId, payload) {
  return apiRequest(`/auth/sessions/${encodeURIComponent(sessionId)}/finish`, {
    method: 'POST',
    body: JSON.stringify(payload),
    keepalive: true,
    timeoutMs: 3000
  })
}

export function finishSessionOnUnload(sessionId, payload) {
  const normalizedSessionId = String(sessionId || '').trim()
  if (!normalizedSessionId || typeof window === 'undefined') {
    return false
  }

  const url = `${getRuntimeApiBaseUrl()}/auth/sessions/${encodeURIComponent(normalizedSessionId)}/finish`
  const body = JSON.stringify(payload || {})

  window.fetch(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      ...buildBearerHeaders()
    },
    body,
    keepalive: true
  }).catch(() => {})
  return true
}
