import type { NextConfig } from "next";
import { BAKED_FUNNELS } from "./src/lib/funnel/bakedFunnels";

const buildVariant =
  process.env.FUNNEL_BUILD_VARIANT ??
  process.env.NEXT_PUBLIC_FUNNEL_BUILD_VARIANT ??
  "frontend";

process.env.FUNNEL_BUILD_VARIANT = buildVariant;
process.env.NEXT_PUBLIC_FUNNEL_BUILD_VARIANT = buildVariant;

/**
 * Генерирует server-side redirects для всех воронок
 * Это обеспечивает мгновенный переход с /[funnelId] на /[funnelId]/[firstScreenId]
 * без промежуточной загрузки страницы (важно для метрик)
 */
function generateFunnelRedirects() {
  const redirects: Array<{
    source: string;
    destination: string;
    permanent: boolean;
  }> = [];

  for (const funnel of Object.values(BAKED_FUNNELS)) {
    const funnelId = funnel.meta.id;
    const firstScreenId = funnel.meta.firstScreenId ?? funnel.screens[0]?.id;

    if (!firstScreenId) {
      console.warn(`Funnel "${funnelId}" has no firstScreenId or screens`);
      continue;
    }

    redirects.push({
      source: `/${funnelId}`,
      destination: `/${funnelId}/${firstScreenId}`,
      permanent: false, // 307 redirect (временный, сохраняет query params и POST данные)
    });
  }

  return redirects;
}

const nextConfig: NextConfig = {
  env: {
    FUNNEL_BUILD_VARIANT: buildVariant,
    NEXT_PUBLIC_FUNNEL_BUILD_VARIANT: buildVariant,
    NEXT_PUBLIC_API_URL: process.env.NEXT_PUBLIC_API_URL,
    DEV_LOGGER_SERVER_ENABLED: process.env.DEV_LOGGER_SERVER_ENABLED,
    NEXT_PUBLIC_AUTH_REDIRECT_URL: process.env.NEXT_PUBLIC_AUTH_REDIRECT_URL,
  },
  
  async redirects() {
    return generateFunnelRedirects();
  },
};

export default nextConfig;
