import * as Sentry from '@sentry/node';
import { nodeProfilingIntegration } from '@sentry/profiling-node';

/**
 * 初始化 Sentry 错误监控
 */
export function initSentry() {
  const dsn = process.env.SENTRY_DSN;
  
  if (!dsn) {
    console.log('[Sentry] 未配置 SENTRY_DSN，错误监控已跳过');
    return false;
  }

  Sentry.init({
    dsn,
    environment: process.env.NODE_ENV || 'development',
    tracesSampleRate: process.env.NODE_ENV === 'production' ? 0.1 : 1.0,
    profilesSampleRate: 1.0,
    integrations: [
      nodeProfilingIntegration(),
    ],
    
    // 错误过滤
    beforeSend(event, hint) {
      // 过滤掉一些无关的错误
      const error = hint.originalException;
      if (error && typeof error === 'object' && 'message' in error) {
        const message = (error as Error).message;
        
        // 忽略一些常见的无关错误
        if (message.includes('ECONNREFUSED') && message.includes('Redis')) {
          return null;
        }
      }
      
      return event;
    },
  });

  console.log('[Sentry] 错误监控已初始化');
  return true;
}

/**
 * 捕获异常
 */
export function captureException(error: Error, context?: Record<string, any>) {
  Sentry.withScope((scope) => {
    if (context) {
      scope.setContext('extra', context);
    }
    Sentry.captureException(error);
  });
}

/**
 * 捕获消息
 */
export function captureMessage(message: string, level?: Sentry.SeverityLevel, context?: Record<string, any>) {
  Sentry.withScope((scope) => {
    if (level) {
      scope.setLevel(level);
    }
    if (context) {
      scope.setContext('extra', context);
    }
    Sentry.captureMessage(message);
  });
}

/**
 * 设置用户上下文
 */
export function setSentryUser(userId: number, email?: string) {
  Sentry.setUser({
    id: String(userId),
    email,
  });
}

/**
 * 设置标签
 */
export function setSentryTag(key: string, value: string) {
  Sentry.setTag(key, value);
}

/**
 * Koa 错误处理中间件
 */
export function sentryErrorHandler() {
  return async (ctx: any, next: any) => {
    try {
      await next();
    } catch (error) {
      if (error instanceof Error) {
        Sentry.withScope((scope) => {
          scope.setTag('method', ctx.method);
          scope.setTag('url', ctx.url);
          scope.setUser({
            id: ctx.state.user?.id ? String(ctx.state.user.id) : undefined,
          });
          Sentry.captureException(error);
        });
      }
      throw error;
    }
  };
}

export default Sentry;
