/**
 * 错误监控服务
 * 生产环境集成 Sentry 后,统一由此模块上报
 * 当前阶段先收集错误信息,等待 Sentry 接入后一键切换
 */

interface ErrorReport {
  type: 'vue' | 'promise' | 'http' | 'runtime'
  message: string
  stack?: string
  component?: string
  source?: string
  url?: string
  timestamp: number
  userAgent: string
}

/** 错误队列:未接入 Sentry 时缓存在内存中 */
const errorQueue: ErrorReport[] = []
const MAX_QUEUE_SIZE = 50

function addToQueue(report: ErrorReport): void {
  errorQueue.push(report)
  if (errorQueue.length > MAX_QUEUE_SIZE) {
    errorQueue.shift()
  }
}

/** 捕获 Vue 错误 */
export function captureVueError(err: Error, instance: any, info: string): void {
  const report: ErrorReport = {
    type: 'vue',
    message: err.message,
    stack: err.stack,
    component: instance?.$options?.name || '未知',
    source: info,
    url: window.location.href,
    timestamp: Date.now(),
    userAgent: navigator.userAgent,
  }
  addToQueue(report)
  // TODO: 接入 Sentry 后替换为 Sentry.captureException(err)
  // import('@sentry/vue').then(Sentry => Sentry.captureException(err))
}

/** 捕获未处理的 Promise 异常 */
export function capturePromiseError(reason: unknown): void {
  const message = reason instanceof Error ? reason.message : String(reason)
  const report: ErrorReport = {
    type: 'promise',
    message,
    stack: reason instanceof Error ? reason.stack : undefined,
    url: window.location.href,
    timestamp: Date.now(),
    userAgent: navigator.userAgent,
  }
  addToQueue(report)
}

/** 捕获 HTTP 错误 */
export function captureHttpError(status: number, url: string, message: string): void {
  addToQueue({
    type: 'http',
    message: `${status} ${url}: ${message}`,
    url: window.location.href,
    timestamp: Date.now(),
    userAgent: navigator.userAgent,
  })
}

/** 获取错误队列(调试用) */
export function getErrorQueue(): ErrorReport[] {
  return [...errorQueue]
}

/** 清空错误队列 */
export function clearErrorQueue(): void {
  errorQueue.length = 0
}