import { resolve } from 'path'
import type { UserConfig } from 'vite'

import { BUILD_CONFIG } from './build.config'
import { moveHtmlToRootPlugin } from './plugins/move-html.plugin'

const projectRoot = resolve(__dirname, '..')
const output = BUILD_CONFIG.OUTPUT.webviews
const server = BUILD_CONFIG.SERVER.webviews

export function getWebviewsConfig(command: 'serve' | 'build'): UserConfig {
  return {
    resolve: {
      dedupe: [
        '@lilara/foundations',
        '@lilara/ui-web-react',
        '@lilara/ui-web',
      ],
    },
    root:
      command === 'serve'
        ? resolve(projectRoot, BUILD_CONFIG.INPUT.webviews.root)
        : projectRoot,

    cacheDir: resolve(projectRoot, BUILD_CONFIG.CACHE_DIR.webviews),
    publicDir: resolve(projectRoot, BUILD_CONFIG.PUBLIC_DIR),
    appType: 'spa',
    base: '/webviews/',

    server: {
      port: server.port,
      host: 'localhost',
    },

    preview: {
      port: server.preview,
      host: 'localhost',
    },

    build: {
      outDir: resolve(projectRoot, output.dir),
      emptyOutDir: true,
      reportCompressedSize: true,
      cssCodeSplit: false,
      commonjsOptions: {
        transformMixedEsModules: true,
      },
      rollupOptions: {
        input: resolve(projectRoot, BUILD_CONFIG.INPUT.webviews.html),
        output: {
          entryFileNames: output.js,
          chunkFileNames: output.js,
          assetFileNames: 'webviews.botonic.[ext]',
        },
      },
    },

    plugins: [
      moveHtmlToRootPlugin(projectRoot, BUILD_CONFIG.TARGET_APPS.WEBVIEWS),
    ],
  }
}
