import path from "path";
import { defineConfig, loadEnv, type Plugin } from "vite";
import react from "@vitejs/plugin-react";
import tailwindcss from "@tailwindcss/vite";

export default defineConfig(({ mode }) => {
	const env = loadEnv(mode, process.cwd(), "");
	const proxyTarget =
		process.env.VITE_DEV_API_PROXY_TARGET ||
		env.VITE_DEV_API_PROXY_TARGET ||
		"http://localhost:8000";
	const appVersion =
		env.VITE_APP_VERSION || process.env.npm_package_version || "0.1.0";
	const appBuildInfo =
		env.VITE_APP_BUILD_INFO ||
		process.env.GIT_COMMIT ||
		process.env.BUILD_COMMIT ||
		"dev";

	return {
		define: {
			__APP_VERSION__: JSON.stringify(appVersion),
			__APP_BUILD_INFO__: JSON.stringify(appBuildInfo),
		},
		plugins: [react(), ...(tailwindcss() as Plugin[])],
		server: {
			proxy: {
				"/api": {
					target: proxyTarget,
					changeOrigin: true,
					secure: false,
				},
				"/grafana": {
					target: "http://localhost:3000",
					changeOrigin: true,
					rewrite: (path: string) => path.replace(/^\/grafana/, ""),
				},
			},
		},
		resolve: {
			alias: {
				"@": path.resolve(__dirname, "./src"),
			},
		},
	};
});
