/** Client-side logger: sends to server, falls back to console. */
const sessionId = ref(null)
const userId = ref(null)

const CONSOLE_METHOD = Object.freeze({ error: 'error', warn: 'warn', info: 'log', debug: 'log' })

export function initLogger(sessId, uid) {
  sessionId.value = sessId
  userId.value = uid
}

function sendToServer(level, message, data) {
  setTimeout(() => {
    $fetch('/api/log', {
      method: 'POST',
      body: { level, message, data, sessionId: sessionId.value, userId: userId.value, timestamp: new Date().toISOString() },
      credentials: 'include',
    }).catch(() => { /* server down - don't spam console */ })
  }, 0)
}

function log(level, message, data) {
  console[CONSOLE_METHOD[level]](`[${message}]`, data)
  sendToServer(level, message, data)
}

export const logError = (message, data) => log('error', message, data)
export const logWarn = (message, data) => log('warn', message, data)
export const logInfo = (message, data) => log('info', message, data)
export const logDebug = (message, data) => log('debug', message, data)
