import react from "@vitejs/plugin-react";
import { defineConfig } from "vite";

// https://vite.dev/config/
export default defineConfig(() => {
	const backendPort = Number(process.env.HUSKIES_PORT || "3001");
	return {
		plugins: [react()],
		define: {
			__HUSKIES_PORT__: JSON.stringify(String(backendPort)),
			__BUILD_TIME__: JSON.stringify(new Date().toISOString()),
		},
		server: {
			port: backendPort + 2172,
			proxy: {
				"/api": {
					target: `http://127.0.0.1:${String(backendPort)}`,
					timeout: 120000,
					configure: (proxy) => {
						proxy.on("error", (_err) => {
							// Swallow proxy errors (e.g. ECONNREFUSED during backend restart)
							// so the vite dev server doesn't crash.
						});
					},
				},
				"/agents": {
					target: `http://127.0.0.1:${String(backendPort)}`,
					timeout: 120000,
					configure: (proxy) => {
						proxy.on("error", (_err) => {});
					},
				},
				"/oauth": {
					target: `http://127.0.0.1:${String(backendPort)}`,
					timeout: 120000,
					configure: (proxy) => {
						proxy.on("error", (_err) => {});
					},
				},
				"/callback": {
					target: `http://127.0.0.1:${String(backendPort)}`,
					timeout: 120000,
					configure: (proxy) => {
						proxy.on("error", (_err) => {});
					},
				},
			},
			watch: {
				ignored: [
					"**/.story_kit/**",
					"**/target/**",
					"**/.git/**",
					"**/server/**",
					"**/Cargo.*",
					"**/vendor/**",
					"**/node_modules/**",
				],
			},
		},
		build: {
			outDir: "dist",
			emptyOutDir: true,
			chunkSizeWarningLimit: 1100,
		},
	};
});
