import { resolve } from 'path'
import type { UserConfig } from 'vite'
import {
  createLogViewerPlugin,
  createWebchatPanelPlugin,
  createWhatsappPanelPlugin,
} from '@botonic/nx-plugin'

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

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

/**
 * Returns the Vite `base` for the webchat bundle.
 *
 * Why this matters: the dashboard's flow-builder preview panel
 * (`PreviewWebchatAppV2`) loads this bundle cross-origin from the bot's Netlify
 * deploy while running on a different origin (localhost:4200 in dev, the
 * dashboard domain in prod). With an absolute base ('/'), Vite resolves the
 * bundle's dynamically-imported chunks as `/chunk.js` against the *host page's*
 * origin — so the preview requests them from the dashboard origin and they 404.
 *
 * A relative base ('') makes those chunks resolve against the entry module's own
 * origin (import.meta.url = Netlify) instead, so the preview loads the whole
 * bundle from Netlify with no chunk 404s and no service-worker proxy. The dev
 * server keeps '/' so its own HMR/asset paths keep working.
 */
function getCrossOriginSafeBase(command: 'serve' | 'build'): string {
  return command === 'build' ? '' : '/'
}

export function getWebchatConfig(command: 'serve' | 'build'): UserConfig {
  const openPath =
    command === 'serve' && process.env.LOG_VIEWER_PORT
      ? `/?logs=${process.env.LOG_VIEWER_PORT}`
      : '/'

  return {
    // For serve mode, use the webchat directory as root so dev server finds index.html
    // For build mode, use project root to avoid relative path issues
    root:
      command === 'serve'
        ? resolve(projectRoot, BUILD_CONFIG.INPUT.webchat.root)
        : projectRoot,

    cacheDir: resolve(projectRoot, BUILD_CONFIG.CACHE_DIR.webchat),
    publicDir: resolve(projectRoot, BUILD_CONFIG.PUBLIC_DIR),
    appType: 'spa',
    base: getCrossOriginSafeBase(command),

    server: {
      port: server.port,
      host: 'localhost',
      open: process.env.VITE_SERVE_OPEN === 'false' ? false : openPath,
      allowedHosts: process.env.VITE_ALLOWED_HOSTS
        ? process.env.VITE_ALLOWED_HOSTS.split(',')
        : [],
    },

    preview: {
      port: server.preview,
      host: 'localhost',
      allowedHosts: process.env.VITE_ALLOWED_HOSTS
        ? process.env.VITE_ALLOWED_HOSTS.split(',')
        : [],
    },

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

    plugins: [
      createLogViewerPlugin(),
      createWhatsappPanelPlugin({
        registeredPhone: process.env.WHATSAPP_PANEL_PHONE,
      }),
      createWebchatPanelPlugin(),
      moveHtmlToRootPlugin(projectRoot, BUILD_CONFIG.TARGET_APPS.WEBCHAT),
    ],
  }
}
