import { type UserConfigExport, type ConfigEnv } from "vite";
import vue from "@vitejs/plugin-vue";
import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import { NaiveUiResolver } from "unplugin-vue-components/resolvers";
import { fileURLToPath, URL } from "node:url";

// https://vite.dev/config/
export default ({ mode }: ConfigEnv): UserConfigExport => {
  const host = process.env.TAURI_DEV_HOST;
  const isProduction = mode === "production";

  return {
    plugins: [
      vue(),
      AutoImport({
        imports: [
          "vue",
          "vue-router",
          "pinia",
          "vue-i18n",
          {
            "naive-ui": [
              "useDialog",
              "useMessage",
              "useNotification",
              "useLoadingBar"
            ]
          }
        ],
        dts: true
      }),
      Components({
        resolvers: [NaiveUiResolver()],
        dts: true
      })
    ],

    resolve: {
      alias: {
        "@": fileURLToPath(new URL("./src", import.meta.url))
      }
    },

    // Vite options tailored for Tauri development
    clearScreen: false,
    server: {
      port: 1420,
      strictPort: true,
      host: host || "0.0.0.0",
      hmr: host
        ? {
            protocol: "ws",
            host,
            port: 1421
          }
        : undefined,
      watch: {
        ignored: ["**/src-tauri/**"]
      }
    },
    build: {
      rollupOptions: {
        output: {
          manualChunks: {
            "vue-vendor": ["vue", "vue-router", "pinia"],
            "naive-ui": ["naive-ui"],
            "tauri-plugins": ["@tauri-apps/plugin-log", "@tauri-apps/api"]
          }
        }
      }
    },
    esbuild: {
      drop: isProduction ? ["console", "debugger"] : []
    }
  };
};
