/**
 * Run `build` or `dev` with `SKIP_ENV_VALIDATION` to skip env validation.
 * This is especially useful for Docker builds.
 */

import { fileURLToPath } from "node:url";
import type { NextConfig } from "next";
import { env } from "~/env";

const withBundleAnalyzer = require("@next/bundle-analyzer")({
	enabled: process.env.ANALYZE === "true",
});

async function createNextConfig(): Promise<NextConfig> {
	const { createJiti } = await import("jiti");
	const jiti = createJiti(fileURLToPath(import.meta.url));

	await jiti.import("./src/env.ts");

	const buildId = `${Date.now().toString(36)}`;
	const apiVersion = `v.${buildId}`;

	const configs: NextConfig = {
		compiler: {
			removeConsole: false,
		},
		experimental: {
			scrollRestoration: true,
			//	esmExternals: "loose",   // This if react-pdf gives compilation issues
		},
		allowedDevOrigins: ["host.docker.internal"],
		generateBuildId: async () => buildId,
		devIndicators: false,
		headers: async () => {
			return [
				{
					source: "/:path*",
					headers: [
						{
							key: "X-Frame-Options",
							value: "",
						},
					],
				},
				{
					source: "/api/trpc/:path*",
					headers: [
						{
							key: "Cache-Control",
							value:
								"no-cache, no-store, must-revalidate, max-age=0, proxy-revalidate",
						},
						{
							key: "X-API-Version",
							value: apiVersion,
						},
						{
							key: "X-Build-ID",
							value: buildId,
						},
					],
				},
			];
		},
		i18n: {
			defaultLocale: "it",
			locales: ["it", "en"],
			localeDetection: false,
		},
		images: {
			unoptimized: true,
			minimumCacheTTL: 7200,
			remotePatterns: [
				{
					hostname: "*.googleusercontent.com",
					pathname: "**",
					port: "",
					protocol: "https",
				},
				{
					hostname: `${env.STORAGE_URL}`,
				},
			],
		},
		output: env.NODE_ENV === "production" ? "standalone" : undefined, // This is for docker builds
		transpilePackages: ["@t3-oss/env-nextjs", "@t3-oss/env-core"],
		reactStrictMode: true,
		rewrites: async () => {
			return [
				{
					destination: env.NODE_ENV === "production" ? "/404" : "/api/panel",
					source: "/api/panel",
				},
			];
		},
		typescript: {
			ignoreBuildErrors: true,
		},
	};

	return withBundleAnalyzer(configs);
}

export default (async () => await createNextConfig())();
