import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import vue from '@vitejs/plugin-vue';
import { build as esbuild } from 'esbuild';
import path from 'path';

function templateJs() {
    const src = path.resolve('src/js/app.js');
    const out = path.resolve('public/assets/js/app.js');

    const compile = () =>
        esbuild({
            entryPoints: [src],
            bundle: true,
            minify: true,
            outfile: out,
        }).catch(console.error);

    return {
        name: 'template-js',
        // runs on: npm run build  /  npm run watch
        buildStart() { return compile(); },
        // runs on: npm run dev
        configureServer(server) {
            compile();
            server.watcher.add(src);
            server.watcher.on('change', (file) => {
                if (file === src) compile();
            });
        },
    };
}

export default defineConfig({
    resolve: {
        alias: {
            '@': path.resolve('resources/js'),
        },
    },
    css: {
        preprocessorOptions: {
            scss: {
                api: 'modern-compiler',
            },
        },
    },
    plugins: [
        templateJs(),
        laravel({
            input: 'resources/js/app.js',
            refresh: true,
        }),
        vue({
            template: {
                transformAssetUrls: {
                    base: null,
                    includeAbsolute: false,
                },
            },
        }),
    ],
});
