import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import tailwindcss from '@tailwindcss/vite'
import path from 'path'
import fs from 'fs'
function builderHotFilePlugin(hotFilePath) {
    return {
        name: 'builder-hot-file',
        configureServer(server) {
            const host =
                server.config.server.host && server.config.server.host !== true
                    ? server.config.server.host
                    : 'localhost'

            const origin = `http://${host}:${server.config.server.port}`

            fs.mkdirSync(path.dirname(hotFilePath), { recursive: true })
            fs.writeFileSync(hotFilePath, origin)

            const cleanup = () => {
                if (fs.existsSync(hotFilePath)) fs.unlinkSync(hotFilePath)
            }

            process.on('exit', cleanup)
            process.on('SIGINT', () => { cleanup(); process.exit() })
            process.on('SIGTERM', () => { cleanup(); process.exit() })
        },
    }
}

export default defineConfig(({ command }) => {
    const isDev = command === 'serve'

    // Dev server schrijft hot-file idealiter naar host public path.
    // Zet dit bij run dev: BUILDER_HOT_FILE=/ABS/PATH/host/public/vendor/builder/core/hot
    const hotFile = process.env.BUILDER_HOT_FILE
        ? path.resolve(process.env.BUILDER_HOT_FILE)
        : path.resolve(__dirname, 'public/hot')

    return {
        root: __dirname,
        plugins: [
            tailwindcss(),
            vue(),
            isDev ? builderHotFilePlugin(hotFile) : undefined,
        ].filter(Boolean),

        publicDir: false,

        // Prod assets worden geserveerd vanaf host: /vendor/builder/core/...
        base: isDev ? '/' : '/vendor/builder/core/',

        // In core wil je overal @builder/ui kunnen importeren
        resolve: {
            alias: {
                '@': path.resolve(__dirname, 'resources/js'),
                '@builder/ui': path.resolve(__dirname, 'resources/js/ui/index.ts'),
            },
        },

        build: {
            manifest: true,
            outDir: 'public',
            emptyOutDir: true,
            // The shared registry chunk (~166 kB gzip) is larger than the default
            // 500 kB minified threshold — it's unavoidable given the two-entry-point
            // architecture (admin + ui). Raise the limit to silence the noise.
            chunkSizeWarningLimit: 1000,
            rollupOptions: {
                // Required so that import-map entries (vue, @builder/ui, inertia)
                // preserve their real export names instead of being renamed to
                // single-letter aliases by Rollup's internal optimiser.
                preserveEntrySignatures: 'strict',
                input: {
                    admin: path.resolve(__dirname, 'resources/js/app.ts'),
                    ui: path.resolve(__dirname, 'resources/js/ui/index.ts'),
                    // Standalone chunks for the import map — shared by all modules
                    'vendor/vue': path.resolve(__dirname, 'resources/js/vendor/vue.ts'),
                    'vendor/inertia': path.resolve(__dirname, 'resources/js/vendor/inertia.ts'),
                },
                output: {
                    manualChunks(id) {
                        if (id.includes('/node_modules/reka-ui/')) return 'vendor-reka';
                        if (id.includes('/node_modules/chart.js/') || id.includes('/node_modules/vue-chartjs/')) return 'vendor-charts';
                        if (id.includes('/node_modules/@tiptap/')) return 'vendor-tiptap';
                    },
                },
            },
        },

        server: {
            port: 5173,
            strictPort: true,
            cors: true,
            hmr: true,
        },
    }
})
