import fs from "node:fs";
import path from "node:path";
import process from "node:process";
import tailwindcss from "@tailwindcss/vite";
import legacy from "@vitejs/plugin-legacy";
import vue from "@vitejs/plugin-vue";
import jsx from "@vitejs/plugin-vue-jsx";
import dotenv from "dotenv";
import autoImport from "unplugin-auto-import/vite";
import iconsResolver from "unplugin-icons/resolver";
import icons from "unplugin-icons/vite";
import { IonicResolver } from "unplugin-vue-components/resolvers";
import components from "unplugin-vue-components/vite";
import { defineConfig } from "vite";
import { VitePWA } from "vite-plugin-pwa";

const packageJson = JSON.parse(fs.readFileSync("./package.json", "utf-8"));
const appVersion = packageJson.version;

// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
  dotenv.config({ path: `.env.${mode}` });

  return {
    plugins: [
      vue(),
      jsx(),
      legacy(),
      icons({
        autoInstall: true,
      }),
      tailwindcss(),
      autoImport({
        dirs: ["src/composables", "src/utils", "src/store"],
        imports: ["vue", "vue-router", "@vueuse/core", "vue-i18n", "pinia"],
        resolvers: [IonicResolver()],
        vueTemplate: true,
      }),
      components({
        directoryAsNamespace: true,
        resolvers: [IonicResolver(), iconsResolver({ prefix: "i" })],
      }),
      VitePWA({
        registerType: "autoUpdate",
        injectRegister: "auto",
        includeAssets: ["favicon.svg"],
        devOptions: {
          enabled: true,
          type: "module",
        },
        manifest: {
          name: "Financial",
          short_name: "Financial",
          description: "Financial",
          theme_color: "#ffffff",
          background_color: "#ffffff",
          display: "standalone",
          orientation: "portrait",
          scope: "/",
          start_url: "/",
          id: "/",
          prefer_related_applications: false,
          icons: [
            {
              src: "/favicon.svg",
              sizes: "any",
              type: "image/svg+xml",
              purpose: "any maskable",
            },
          ],
        },
        workbox: {
          globPatterns: ["**/*.{js,css,html,ico,png,svg,jpg,woff2}"],
          navigateFallback: "/index.html",
          navigateFallbackDenylist: [/^\/api/],
          cleanupOutdatedCaches: true,
          clientsClaim: true,
          skipWaiting: true,
          maximumFileSizeToCacheInBytes: 3 * 1024 * 1024, // 3 MB
        },
      }),
    ],
    define: {
      __APP_VERSION__: JSON.stringify(appVersion),
    },
    resolve: {
      alias: {
        "@": path.resolve(__dirname, "./src"),
      },
    },
    server: {
      host: true,
      proxy: {
        "/api": {
          target: process.env.VITE_API_URL,
          changeOrigin: true,
          ws: true,
        },
      },
    },
  };
});
