/// <reference types="vitest" />
import { fileURLToPath, URL } from "node:url";
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import vuetify from "vite-plugin-vuetify";
import eslintPlugin from "vite-plugin-eslint";
import basicSsl from "@vitejs/plugin-basic-ssl";
import { viteExternalsPlugin } from "vite-plugin-externals";
import cssInjectedByJsPlugin from "vite-plugin-css-injected-by-js";
import { globSync } from "glob";
import fs from "fs";
import path from "path";

const LIB_FOLDER = "dist/external-components";

if (!fs.existsSync(LIB_FOLDER)) {
  fs.mkdirSync(LIB_FOLDER, { recursive: true });
}

function copyFile(from: string, to: string, overwrite = false) {
  if (overwrite || !fs.existsSync(to)) {
    fs.copyFileSync(path.resolve(from), path.resolve(to));
  }
}

function copyFiles(targets: { from: string; to: string }[], overwrite = false) {
  return {
    name: "copy-files",
    generateBundle() {
      targets.forEach(({ from, to }) => {
        if (!fs.existsSync(LIB_FOLDER)) {
          fs.mkdirSync(LIB_FOLDER, { recursive: true });
        }

        if (!fs.existsSync(from)) {
          return;
        }

        if (fs.lstatSync(from).isDirectory()) {
          fs.readdirSync(from).forEach((file) => {
            const fromFile = `${from}/${file}`;
            const toFile = `${to}/${file}`;
            copyFile(fromFile, toFile, overwrite);
          });
        } else if (fs.lstatSync(from).isFile()) {
          copyFile(from, to, overwrite);
        }
      });
    },
  };
}

export default defineConfig({
  plugins: [
    vue(),
    vuetify({ autoImport: true }),
    eslintPlugin(),
    basicSsl(),
    viteExternalsPlugin({
      vue: "Vue",
      vuetify: "Vuetify",
      pinia: "Pinia",
      "vue-i18n": "VueI18n",
      "vue-router": "VueRouter",
      "@actindo/core-ui": "ActindoCoreUI",
      // vuedraggable: "VueDraggable",
      // "@vuelidate/core": "VuelidateCore",
      // "@vuelidate/validators": "VuelidateValidators",
    }),
    cssInjectedByJsPlugin({ relativeCSSInjection: true }),
    copyFiles([
      {
        from: "./src/locales/en-US.external.json",
        to: `./${LIB_FOLDER}/en-US.json`,
      },
      {
        from: "./src/locales/de-DE.external.json",
        to: `./${LIB_FOLDER}/de-DE.json`,
      },
    ]),
  ],
  define: { "process.env": {} },
  envPrefix: "CORE1_",
  resolve: {
    alias: {
      "@": fileURLToPath(new URL("./src", import.meta.url)),
    },
  },
  build: {
    minify: false, // debug only
    sourcemap: true, // debug only
    cssCodeSplit: true,
    outDir: LIB_FOLDER,
    lib: {
      entry: globSync("src/components/dataTypes/**/*.vue"),
      // entry: [
      //   "src/components/dataTypes/StringValue/DatahubBadWordFilter.vue",
      //   "src/components/dataTypes/StringValue/DatahubDataTypeStringValue.vue",
      // ],
      formats: ["es"],
    },
    copyPublicDir: false,
    rollupOptions: {
      output: {
        preserveModules: false,
      },
    },
  },
});
