import type { NextConfig } from "next";
import { withSentryConfig } from "@sentry/nextjs";

const nextConfig: NextConfig = {
  reactStrictMode: true,
  output: "standalone",
  images: {
    remotePatterns: [
      { protocol: "https", hostname: "xn--80az8a.xn--d1aqf.xn--p1ai" },
      { protocol: "https", hostname: "наш.дом.рф" },
    ],
    formats: ["image/webp"],
    minimumCacheTTL: 60 * 60 * 24 * 7,
  },
  // In dev (no Caddy) Next.js itself proxies /api/* and /health to the backend
  // so the browser can use same-origin relative URLs.
  // In prod Caddy intercepts these paths before they reach Next.js,
  // so these rewrites are effectively a no-op there.
  async rewrites() {
    const backend = process.env.BACKEND_URL ?? "http://localhost:8000";
    return [
      { source: "/api/:path*", destination: `${backend}/api/:path*` },
      { source: "/health", destination: `${backend}/health` },
    ];
  },
  // /sf — короткий алиас для /site-finder (legacy short URL).
  async redirects() {
    return [
      { source: "/sf", destination: "/site-finder", permanent: true },
      {
        source: "/sf/:path*",
        destination: "/site-finder/:path*",
        permanent: true,
      },
    ];
  },
  // Markdown в public/docs/ — отдаём с text/markdown + charset, чтобы
  // браузер показывал inline (не download).
  async headers() {
    return [
      {
        source: "/docs/:path*.md",
        headers: [
          { key: "Content-Type", value: "text/markdown; charset=utf-8" },
        ],
      },
    ];
  },
};

export default withSentryConfig(nextConfig, {
  org: process.env.SENTRY_ORG ?? "gendesign",
  project: process.env.SENTRY_PROJECT ?? "frontend",
  sentryUrl: process.env.SENTRY_URL ?? "https://errors.gendsgn.ru/",
  // Only upload source maps when auth token is present (CI builds).
  // Without authToken the upload step is silently skipped.
  authToken: process.env.GLITCHTIP_AUTH_TOKEN,
  silent: !process.env.CI,
  widenClientFileUpload: true,
  // Delete generated source maps from the build output after upload to
  // prevent them from being served publicly.
  sourcemaps: {
    deleteSourcemapsAfterUpload: true,
  },
  // No tunnel route — GlitchTip is not behind a CORS proxy
  tunnelRoute: undefined,
  // Webpack-specific options
  webpack: {
    // Treeshake Sentry SDK logger statements from the bundle
    treeshake: {
      removeDebugLogging: true,
    },
    // Not deploying on Vercel — no cron monitors needed
    automaticVercelMonitors: false,
  },
});
