import * as Sentry from "@sentry/node"
import { nodeProfilingIntegration } from "@sentry/profiling-node"
import { prismaIntegration } from "@sentry/node"

const isProduction = process.env.NODE_ENV === "production"
const environment = process.env.AZURE_ENVIRONMENT || process.env.NODE_ENV || "development"

Sentry.init({
  dsn: isProduction
    ? "https://7a83ac92f85c298f31bae97b97cabfe2@o4506833230561280.ingest.sentry.io/4506833372643328"
    : undefined,

  environment,

  integrations: [
    nodeProfilingIntegration(),
    prismaIntegration(), // Better database error tracking
  ],

  // Performance Monitoring sampling rate
  // In production, sample 20% of transactions to reduce noise
  tracesSampleRate: isProduction ? 0.2 : 1.0,

  // Profiling sampling rate
  // In production, sample 10% of transactions
  profilesSampleRate: isProduction ? 0.1 : 1.0,

  // Debug mode for local testing
  debug: !isProduction,

  // Capture more context for errors
  maxBreadcrumbs: 50,

  // Attach stack traces to messages
  attachStacktrace: true,

  // Add release information if available
  release: process.env.RELEASE_VERSION || process.env.npm_package_version,

  // Filter out sensitive data
  beforeSend(event, hint) {
    // Remove sensitive headers
    if (event.request?.headers) {
      delete event.request.headers.authorization
      delete event.request.headers.cookie
      delete event.request.headers["x-api-key"]
    }

    // Remove sensitive environment variables
    if (event.contexts?.runtime?.env) {
      const sensitiveKeys = ["DATABASE_URL", "STRIPE_SECRET", "JWT_SECRET", "GITHUB_PRIVATE_KEY"]
      sensitiveKeys.forEach(key => {
        if (event.contexts?.runtime?.env) {
          delete event.contexts.runtime.env[key]
        }
      })
    }

    return event
  },

  // Ignore certain errors
  ignoreErrors: [
    // Browser extensions
    "top.GLOBALS",
    // Random plugins/extensions
    "originalCreateNotification",
    "canvas.contentDocument",
    "MyApp_RemoveAllHighlights",
    // Common benign errors
    "Non-Error promise rejection captured",
    "ResizeObserver loop limit exceeded",
    // Network errors that are user-side issues
    "Network request failed",
    "NetworkError",
  ],

  // Add server name for identification
  serverName: process.env.WEBSITE_INSTANCE_ID || process.env.HOSTNAME || "unknown",

  // Tag with Azure-specific metadata if available
  initialScope: {
    tags: {
      service: "cf-api",
      azure_instance: process.env.WEBSITE_INSTANCE_ID || "unknown",
      azure_site_name: process.env.WEBSITE_SITE_NAME || "unknown",
      node_version: process.version,
    },
  },
})
