import { defineConfig } from 'vite';
import { resolve } from 'path';
import { VitePWA } from 'vite-plugin-pwa';
import * as fs from 'node:fs';

export default defineConfig({
    build: {
        outDir: 'public',  // Direct output to public directory
        manifest: '.vite/manifest.json',  // Put manifest in .vite subfolder
        emptyOutDir: false,  // Don't delete existing public files
        assetsDir: 'assets',
        
        // Performance optimizations
        minify: 'terser',
        terserOptions: {
            compress: {
                drop_console: false,  // Keep console.log for debugging
                drop_debugger: true
            }
        },
        
        // Chunk optimization to prevent excessive fragmentation
        rollupOptions: {
            input: {
                main: resolve(import.meta.dirname, 'resources/js/main.js'),
                admin: resolve(import.meta.dirname, 'resources/css/admin/admin.css')
            },
            output: {
                // Simplified chunking - disable manual chunking to let Vite handle it naturally
                // manualChunks: undefined,
                
                // Optimize chunk sizes
                chunkFileNames: 'assets/js/[name]-[hash].js',
                entryFileNames: 'assets/js/[name]-[hash].js',
                assetFileNames: (assetInfo) => {
                    const info = assetInfo.name.split('.');
                    const ext = info[info.length - 1];
                    
                    if (/\.(png|jpe?g|svg|gif|tiff|bmp|ico)$/i.test(assetInfo.name)) {
                        return `assets/images/[name]-[hash].${ext}`;
                    }
                    
                    if (/\.css$/i.test(assetInfo.name)) {
                        return `assets/css/[name]-[hash].${ext}`;
                    }
                    
                    return `assets/[name]-[hash].${ext}`;
                }
            }
        },
        
        // Compression and optimization
        reportCompressedSize: true,
        chunkSizeWarningLimit: 1000,
        
        // Source maps for production debugging
        sourcemap: 'hidden'
    },
    
    plugins: [
        // PWA plugin temporarily disabled due to build issues
        // VitePWA({ ... })
    ],
    
    // Optimized development server
    server: {
        https: (() => {
            try {
                if (fs.existsSync('./ssl/localhost.pem') && fs.existsSync('./ssl/localhost-key.pem')) {
                    return {
                        key: fs.readFileSync('./ssl/localhost-key.pem'),
                        cert: fs.readFileSync('./ssl/localhost.pem')
                    };
                }
            } catch (error) {
                console.warn('SSL certificates not found, falling back to HTTP');
            }
            return false;
        })(),
        host: true,
        port: 3000,
        open: false,
        hmr: {
            overlay: true
        }
    },
    
    // CSS optimization
    css: {
        devSourcemap: true,
        preprocessorOptions: {
            scss: {
                additionalData: '@import "resources/css/settings/variables.css";'
            }
        }
    },
    
    // Dependency optimization
    optimizeDeps: {
        include: [
            // Pre-bundle known dependencies
        ],
        exclude: [
            // Exclude problematic dependencies
        ]
    },
    
    // Asset handling
    assetsInclude: ['**/*.woff2', '**/*.woff', '**/*.ttf'],
    
    // Development environment
    define: {
        __DEV__: JSON.stringify(process.env.NODE_ENV !== 'production')
    }
});
