import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import dts from 'vite-plugin-dts'

// Second build pass: chart subpath entry. Runs AFTER the main `vite build`
// with emptyOutDir:false so it augments dist/ without wiping index artifacts.
// ESM-only (multi-format UMD is reserved for the single-entry index build).
export default defineConfig({
  plugins: [
    vue(),
    // rollupTypes:true was tried and rejected: vite-plugin-dts resolves its
    // rolled-up output filename from package.json's "types" field (dist/index.d.ts),
    // which collides with and clobbers the main build's index.d.ts (verified: it
    // overwrote index.d.ts with chart-unrelated content and never emitted chart.d.ts).
    // Fallback: widen `include` to cover the whole reference chain so vite-plugin-dts
    // emits per-file declarations (dist/canonical/Chart.vue.d.ts, dist/components/Chart/*.d.ts)
    // instead of relying on rollup to flatten them.
    dts({
      include: ['src/chart.ts', 'src/canonical/Chart.vue', 'src/components/Chart/**'],
      insertTypesEntry: true,
    }),
  ],
  build: {
    emptyOutDir: false,
    lib: {
      entry: fileURLToPath(new URL('src/chart.ts', import.meta.url)),
      formats: ['es'],
      fileName: () => 'chart.js',
    },
    cssCodeSplit: false,
    rollupOptions: {
      external: ['vue'],
      output: {
        assetFileNames: (info) =>
          info.name && info.name.endsWith('.css') ? 'chart/style.css' : 'assets/[name]-[hash][extname]',
      },
    },
  },
})
