import { copyFileSync, existsSync, rmSync } from 'fs'
import { resolve } from 'path'
import type { Plugin } from 'vite'

import { BUILD_CONFIG, type ClientTargetApp } from '../build.config'

export function moveHtmlToRootPlugin(
  projectRoot: string,
  targetApp: ClientTargetApp
): Plugin {
  return {
    name: 'move-html-to-root',
    apply: 'build',
    closeBundle() {
      const outputConfig = BUILD_CONFIG.OUTPUT[targetApp]
      const inputConfig = BUILD_CONFIG.INPUT[targetApp]

      const distDir = resolve(projectRoot, outputConfig.dir)
      const srcDir = resolve(distDir, 'src')

      if (existsSync(srcDir)) {
        const nestedHtml = resolve(distDir, inputConfig.html)
        const targetHtml = resolve(distDir, outputConfig.html)

        if (existsSync(nestedHtml)) {
          // Move the HTML file to root
          copyFileSync(nestedHtml, targetHtml)
          // Remove the src directory
          rmSync(srcDir, { recursive: true, force: true })
          console.log(`✓ Moved ${outputConfig.html} to ${outputConfig.dir}/`)
        }
      }
    },
  }
}

