const isDev =
  typeof process !== 'undefined' &&
  Boolean(process.env?.DEV)

function emit(level, scope, message, data = {}) {
  const payload = {
    time: new Date().toISOString(),
    level,
    scope,
    message,
    ...data
  }

  const text = `[${scope}] ${message}`

  if (level === 'error') {
    console.error(text, payload)
    return
  }
  if (level === 'warn') {
    console.warn(text, payload)
    return
  }
  if (level === 'debug' && !isDev) {
    return
  }

  console.info(text, payload)
}

export function createTraceId(prefix = 'trace') {
  const rawId =
    typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function'
      ? crypto.randomUUID()
      : `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`

  return `${prefix}-${rawId}`
}

export const slog = {
  debug(scope, message, data = {}) {
    emit('debug', scope, message, data)
  },
  info(scope, message, data = {}) {
    emit('info', scope, message, data)
  },
  warn(scope, message, data = {}) {
    emit('warn', scope, message, data)
  },
  error(scope, message, data = {}) {
    emit('error', scope, message, data)
  }
}
