import { defineConfig } from 'vite';
import { svelte } from '@sveltejs/vite-plugin-svelte';
//import viteCompression from 'vite-plugin-compression';
import fs from 'fs';
import path from 'path';
import child_process from 'child_process';

let key: Buffer | null = null;
let cert: Buffer | null = null;

const isProduction = process.env.NODE_ENV === 'production';

if (!isProduction) {
    const baseFolder =
        process.env.APPDATA !== undefined && process.env.APPDATA !== ''
            ? `${process.env.APPDATA}/ASP.NET/https`
            : `${process.env.HOME}/.aspnet/https`;

    const certificateArg = process.argv.map(arg => { const match = arg.match(/--name=(.+)/i); return match ? match[1] : null; }).filter(Boolean)[0];
    const certificateName = certificateArg ? certificateArg : "pgo-koppelvlak-doel-frontend";

    if (!certificateName) {
        console.error('Invalid certificate name. Run this script in the context of an npm/yarn script or pass --name=<<app>> explicitly.')
        process.exit(-1);
    }

    const certFilePath = path.join(baseFolder, `${certificateName}.pem`);
    const keyFilePath = path.join(baseFolder, `${certificateName}.key`);

    if (!fs.existsSync(certFilePath) || !fs.existsSync(keyFilePath)) {
        if (0 !== child_process.spawnSync('dotnet', [
            'dev-certs',
            'https',
            '--export-path',
            certFilePath,
            '--format',
            'Pem',
            '--no-password',
        ], { stdio: 'inherit', }).status) {
            throw new Error("Could not create certificate.");
        }
    }

    key = fs.readFileSync(keyFilePath);
    cert = fs.readFileSync(certFilePath);
}

// https://vitejs.dev/config/
export default defineConfig({
    //base: './',
    plugins: [svelte(),
    //    viteCompression({
    //        verbose: true,            // Enable console output for debugging
    //        disable: false,           // Enable gzip compression
    //        threshold: 10240,         // Minimum file size to compress (in bytes)
    //        algorithm: 'gzip',        // Use gzip compression
    //        ext: '.gz',               // Add .gz extension to compressed files
    //        //algorithm: 'brotliCompress',  // Use Brotli compression
    //        //ext: '.br',                   // Add .br extension for Brotli files
    //        deleteOriginFile: false,  // Do not delete original files
    //    }),
    ],
    build: {
        minify: 'terser', // Minify JavaScript and CSS (default in production mode)
        //terserOptions: {
        //    compress: {
        //        drop_console: true,    // Optionally remove console.log statements in production
        //    },
        //},
    },
    server: { 
        proxy: {
            '^/api/.*': {
                target: 'https://localhost:5102/',
                secure: false
            },
            '^/bff/.*': {
                target: 'https://localhost:5102/',
                secure: false
            },
            '^/signin-oidc': {
                target: 'https://localhost:5102/',
                secure: false
            },
            '^/signout-callback-oidc': {
                target: 'https://localhost:5102/',
                secure: false
            },
        },
        port: 5002,
        https: {
            key: key,
            cert: cert,
        }
    }
})
