/**
 * Vite Configuration for Shared FlowDrop Library
 *
 * Builds a single shared library containing both workflow editor and
 * schema form functionality for use across Drupal SDC components.
 *
 * Output: build/flowdrop.iife.js, build/flowdrop.es.js
 * Global: window.FlowDrop
 */

import { defineConfig } from "vite";
import { svelte } from "@sveltejs/vite-plugin-svelte";
import path from "path";

export default defineConfig({
	plugins: [
		svelte({
			compilerOptions: {
				dev: false
			},
			onwarn: (warning, handler) => {
				if (warning.filename?.includes("node_modules")) {
					return;
				}
				handler(warning);
			}
		})
	],
	resolve: {
		alias: {
			$lib: path.resolve("./src/lib"),
			"$app/stores": path.resolve("./src/lib/mocks/app-stores.js"),
			"$app/forms": path.resolve("./src/lib/mocks/app-forms.js"),
			"$app/navigation": path.resolve("./src/lib/mocks/app-navigation.js"),
			"$app/environment": path.resolve("./src/lib/mocks/app-environment.js")
		},
		conditions: ["svelte", "browser", "import"],
		dedupe: ["svelte"]
	},
	build: {
		outDir: "build",
		lib: {
			entry: "src/lib/index.ts",
			name: "FlowDrop",
			fileName: (format) => `flowdrop.${format}.js`,
			formats: ["iife", "es"]
		},
		rollupOptions: {
			external: [],
			output: {
				globals: {},
				assetFileNames: (assetInfo) => {
					if (assetInfo.name?.endsWith(".css")) {
						return "flowdrop.css";
					}
					return assetInfo.name || "assets/[name]-[hash][extname]";
				},
				inlineDynamicImports: true
			}
		},
		sourcemap: true,
		minify: "terser",
		terserOptions: {
			compress: {
				drop_console: false,
				drop_debugger: true
			}
		},
		target: "es2020",
		chunkSizeWarningLimit: 5000,
		commonjsOptions: {
			include: [/node_modules/],
			transformMixedEsModules: true
		}
	},
	define: {
		"process.env.NODE_ENV": JSON.stringify("production"),
		"process.env": "{}",
		"import.meta.env.MODE": JSON.stringify("production"),
		"import.meta.env.DEV": "false",
		"import.meta.env.PROD": "true",
		"import.meta.env.SSR": "false"
	},
	envPrefix: "__FLOWDROP_DISABLED__",
	optimizeDeps: {
		include: [
			"@d34dman/flowdrop",
			"svelte",
			"@xyflow/svelte",
			"@iconify/svelte",
			"uuid"
		],
		exclude: []
	}
});
