import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import fs from 'node:fs';
import JavascriptObfuscator from "javascript-obfuscator";
import lib from "@minify-html/node";

export default defineConfig(({mode}) => ({
    plugins: [
        react(),
        {
            name: 'add-nonce-back',
            transformIndexHtml(html) {
                const nonce = '**MY_PRETTY_CSP_NONCE**';
                return html.replace(
                    /<script\s+type="module"\s+crossorigin\s+src="\/autocart\.js"\s*>/,
                    (match) => {
                        return `<script type="module" crossorigin nonce="${nonce}" src="/autocart.js">`;
                    }
                );
            },
        },
        mode === 'production' && {
            name: 'copy-html-root',
            closeBundle() {
                fs.copyFileSync('dist/src/template.html', 'auto_cart.html');
                fs.writeFileSync('auto_cart.html', fs.readFileSync('dist/src/template.html').toString().replace('autocart.js', 'autocart.js?' + Math.random()));
                fs.copyFileSync('src_static/cookies_and_recommendations.html', 'land/cookies_and_recommendations.html');
                fs.writeFileSync('autocart.js', JavascriptObfuscator.obfuscate(fs.readFileSync('dist/autocart.js').toString()
                    .replace('https://local.hvatilo.ru:8055', 'https://hvatilo.ru')
                ).getObfuscatedCode());
                fs.writeFileSync('index.html', lib.minify(fs.readFileSync('src_static/index.html'), {
                    minify_css: true,
                    minify_js: true,
                    keep_comments: false,
                    keep_ssi_comments: false,
                }));
            },
        },
    ],
    ...(mode != 'production' && {
        server: {
            host: 'local.hvatilo.ru',
            port: 9876,
            https: {
                cert: fs.readFileSync('local.hvatilo.ru.pem'),
                key: fs.readFileSync('local.hvatilo.ru-key.pem'),
            },
            open: '/src/template.html',
        }
    }),
    input: {
        main: './src/template.html',
    },
    build: {
        outDir: 'dist',
        rolldownOptions: {
            output: {
                entryFileNames: 'autocart.js',
                chunkFileNames: 'chunk.js',
                assetFileNames: 'plugin.css',
            },
        }
    },
}));