/**
 * @file Vite Configuration for Electron Platform
 * @author Matthew Raymer
 * 
 * This configuration file sets up Vite for building the TimeSafari application
 * for the Electron desktop platform. It extends the common configuration with
 * electron-specific settings and optimizations.
 * 
 * Key Features:
 * - Electron-specific platform detection
 * - Desktop-optimized build settings
 * - Capacitor-Electron plugin integration
 * - Native module support
 * - Desktop-specific asset handling
 * 
 * Usage:
 * ```bash
 * vite build --config vite.config.electron.mts
 * ```
 * 
 * Environment Variables:
 * - VITE_PLATFORM: Set to "electron"
 * - PWA: Disabled for desktop (via build exclusion)
 */

import { defineConfig } from "vite";
import { createBuildConfig } from "./vite.config.common.mts";

export default defineConfig(async () => {
  const baseConfig = await createBuildConfig("electron");
  
  return {
    ...baseConfig,
    
    plugins: [
      ...baseConfig.plugins || [],
      // Plugin to replace the main entry point for electron builds
      {
        name: 'electron-entry-point',
        transformIndexHtml(html) {
          return html.replace(
            '/src/main.web.ts',
            '/src/main.electron.ts'
          );
        }
      },
      // Plugin to handle Electron-specific configurations
      {
        name: 'electron-config',
        config(config) {
          // Suppress console warnings about missing source maps for external deps
          if (config.build && config.build.rollupOptions) {
            config.build.rollupOptions.onwarn = (warning, warn) => {
              // Suppress warnings about missing source maps for external modules
              if (warning.code === 'MISSING_GLOBAL_NAME' || 
                  warning.message?.includes('sourcemap') ||
                  warning.message?.includes('@capacitor-community/sqlite')) {
                return;
              }
              warn(warning);
            };
          }
        }
      },
      // Plugin to suppress source map loading for external modules
      {
        name: 'suppress-source-maps',
        transformIndexHtml(html) {
          // Add script to suppress source map loading errors
          const script = `
            <script>
              // Suppress source map loading errors for external modules
              const originalFetch = window.fetch;
              window.fetch = function(url, options) {
                if (typeof url === 'string' && url.includes('.map')) {
                  console.log('[Source Map] Suppressed loading of:', url);
                  return Promise.resolve(new Response('', { status: 404 }));
                }
                return originalFetch(url, options);
              };
            </script>
          `;
          return html.replace('</head>', script + '</head>');
        }
      }
    ],
    
    // Electron-specific entry point
    build: {
      ...baseConfig.build,
      outDir: "dist",
      // Disable source maps for Electron to prevent DevTools warnings
      sourcemap: false,
      // Use the electron-specific main entry point
      rollupOptions: {
        ...baseConfig.build?.rollupOptions,
        // Electron-specific externals
        external: [
          "electron",
          "@capacitor-community/electron",
          "better-sqlite3-multiple-ciphers"
        ],
        output: {
          ...baseConfig.build?.rollupOptions?.output,
          // Desktop can handle larger chunks
          manualChunks: {
            vendor: ["vue", "vue-router", "@vueuse/core"],
            crypto: ["@nostr/tools", "crypto-js"],
            ui: ["@fortawesome/vue-fontawesome"]
          }
        }
      },
      // Electron doesn't need ES module compatibility
      target: "node16",
      // Optimize for desktop performance
      chunkSizeWarningLimit: 2000
    },
    
    // Electron-specific optimizations
    optimizeDeps: {
      ...baseConfig.optimizeDeps,
      // Include electron-specific dependencies
      include: [
        ...(baseConfig.optimizeDeps?.include || []),
        "@capacitor-community/electron"
      ],
      // Exclude native modules that Electron will handle
      exclude: [
        ...(baseConfig.optimizeDeps?.exclude || []),
        "better-sqlite3-multiple-ciphers",
        "electron"
      ]
    },
    
    // Electron doesn't need dev server configuration
    server: undefined,
    
    // Desktop-specific environment
    define: {
      ...baseConfig.define,
      'process.env.VITE_PLATFORM': JSON.stringify('electron'),

      
      // Electron-specific flags
      '__ELECTRON__': JSON.stringify(true),
      '__IS_DESKTOP__': JSON.stringify(true),
      '__USE_NATIVE_SQLITE__': JSON.stringify(true)
    }
  };
}); 