import * as path from 'path';
import {defineConfig} from 'vite';
import react from '@vitejs/plugin-react-swc';
import inject from "@rollup/plugin-inject";

const ROOT = path.resolve('../../../')
const BASE = __dirname.replace(ROOT, '');

export default defineConfig({
    base: process.env.NODE_ENV === 'production' ? `${BASE}/dist/` : '',
    define: {},
    resolve: {
        alias: {
            '@': path.resolve(__dirname, './src'),
            'tailwind-config': path.resolve(__dirname, './tailwind.config.cjs'),
        },
    },
    optimizeDeps: {
        exclude: ['fsevents'],
    },
    build: {
        manifest: true,
        assetsDir: '.',
        outDir: `dist`,
        emptyOutDir: true,
        //sourcemap: true,
        //sourcemap: 'inline', DO NOT INLINE IT OR ELSE THE BUILD IS LITERALLY HUGE (11MB!)
        rollupOptions: {
            input: [
                'src/main.tsx',
                'src/App.css',
            ],
            output: {
                entryFileNames: '[hash].js',
                chunkFileNames: '[hash].js',
                assetFileNames: '[hash].[ext]',
            }
        },
    },
    plugins: [
        {
            name: 'move-manifest',
            closeBundle() {
                const fs = require('fs');
                const path = require('path');
                const manifestDir = path.resolve(__dirname, 'dist/.vite');
                const manifestFile = path.join(manifestDir, 'manifest.json');
                const targetFile = path.resolve(__dirname, 'dist/manifest.json');

                if (fs.existsSync(manifestFile)) {
                    const manifest = fs.readFileSync(manifestFile, 'utf-8');
                    fs.writeFileSync(targetFile, manifest);
                    // Optionally remove the .vite directory
                    fs.rmSync(manifestDir, { recursive: true, force: true });
                }
            }
        },
        react(),
        inject({
            include: ['src/**/*.{js,jsx,ts,tsx}'],
            exclude: ['node_modules/**'],
            // Inject variables from src/globals.ts
            $: [path.resolve(__dirname, 'src/globals.ts'), '$'],
            CouponsPlus: [path.resolve(__dirname, 'src/globals.ts'), 'CouponsPlus'],
            __: [path.resolve(__dirname, 'src/globals.ts'), '__'],
        }),
        {
            name: 'php',
            handleHotUpdate({file, server}) {
                if (file.endsWith('.php')) {
                    server.ws.send({type: 'full-reload'});
                }
            },
        }
    ],
    server: {
        // we need a strict port to match on PHP side
        // change freely, but update on PHP to match the same port
        // tip: choose a different port per project to run them at the same time
        strictPort: true,
        port: 5173,
        cors: {
            origin: 'https://coupons-plus.test',
        },
        watch: {
            usePolling: true,
            interval: 1000,
        },
    },

});
