import {defineConfig, loadEnv} from 'vite'
import vuetify, {transformAssetUrls} from "vite-plugin-vuetify";
import dts from "vite-plugin-dts";
import Vue from "@vitejs/plugin-vue";
import Vuetify from "vite-plugin-vuetify";
import path from 'path';

export default defineConfig(({command, mode}) => {
  const env = loadEnv(mode, process.cwd(), '')
  const VITE_BASE_URL = env.VITE_BASE_URL || '';
  console.log('Asset URL: ' + VITE_BASE_URL);
  console.log('Mode:' + mode)
  console.log('Command:' + command)
  if (command === 'serve') {
    return {  // dev specific config
      server: {
        proxy: {
          '/api': {
            target: 'http://localhost:8080',
            changeOrigin: true,
            rewrite: (path) => {
              const newPath = path.replace(/^\//, '');
              console.log("Rewritten API URL: ", newPath);
              return newPath;
            }
          }
        }
      },
      resolve: {
        alias: {
          '@': path.resolve(__dirname, './src'),
        },
      },
      plugins: [
        Vue({
          template: { transformAssetUrls: transformAssetUrls },
        }),
        Vuetify({
          autoImport: true,
          styles: {
            configFile: 'src/styles/settings.scss',
          },
        }),
      ],
    }
  } else {     // command === 'build'
    return {
      plugins: [ Vue({
            isProduction: true,
            template: { transformAssetUrls },
            features: { propsDestructure : true}
          }
      ), vuetify({ styles: 'none' }),
        dts({exclude: ['node_modules','dist','.storybook']})],
      resolve: {
        alias: {
          '@': path.resolve(__dirname, './src'),
        },
      },
      build: {
        assetsInlineLimit: 0, // Prevent inlining images as Base64
        minify: true,
        emptyOutDir: true,
        target: 'esnext',
        modulePreload: {polyfill: false},
        rollupOptions: {
          output: {
            assetFileNames: 'assets/[name].[hash][extname]'
          },
        },
      },
      base: `${VITE_BASE_URL}`
    }
  }
})
