// Next.js instrumentation hook — runs once when the server process starts.
// (1) Initializes Sentry for the active runtime, and (2) surfaces "silently
// disabled" integrations at boot so a misconfigured deploy is obvious in the
// logs instead of failing quietly at runtime.
import * as Sentry from "@sentry/nextjs"

export async function register() {
  // Initialize Sentry for whichever server runtime is booting.
  if (process.env.NEXT_RUNTIME === "nodejs") {
    await import("./sentry.server.config")
  }
  if (process.env.NEXT_RUNTIME === "edge") {
    await import("./sentry.edge.config")
  }

  // --- Startup env warnings (Node.js server runtime, production only) ---
  if (process.env.NEXT_RUNTIME !== "nodejs") return
  if (process.env.NODE_ENV !== "production") return

  const warn = (msg: string) => console.warn(`[startup] ⚠ ${msg}`)

  const spacesConfigured =
    process.env.SPACES_KEY && process.env.SPACES_SECRET && process.env.SPACES_BUCKET
  if (!spacesConfigured) {
    warn(
      "Object storage (SPACES_*) is NOT configured — uploads fall back to local disk, " +
        "which is EPHEMERAL on App Platform. Uploaded files are lost on every deploy/restart. " +
        "Configure DigitalOcean Spaces."
    )
  }

  const smtpConfigured = process.env.SMTP_HOST && process.env.SMTP_USER && process.env.SMTP_PASS
  if (!smtpConfigured) {
    warn(
      "SMTP (SMTP_HOST / SMTP_USER / SMTP_PASS) is NOT configured — all outbound email " +
        "(rent reminders, overdue/lease alerts, team invites, password resets) will silently fail."
    )
  }

  if (!process.env.STRIPE_SECRET_KEY) {
    warn("STRIPE_SECRET_KEY is NOT set — checkout/billing and rent payment links are disabled.")
  }

  if (!process.env.OPENAI_API_KEY) {
    warn("OPENAI_API_KEY is NOT set — AI features will error when called.")
  }

  if (!process.env.SENTRY_DSN && !process.env.NEXT_PUBLIC_SENTRY_DSN) {
    warn("SENTRY DSN is NOT set — error monitoring is disabled (no crash reports).")
  }
}

// Capture errors thrown in nested React Server Components, route handlers, and
// server actions and report them to Sentry.
export const onRequestError = Sentry.captureRequestError
