import { defineConfig } from "vite";
import path from 'path';

export default defineConfig({
  build: {
    outDir: 'dist-electron',
    rollupOptions: {
      input: {
        main: path.resolve(__dirname, 'src/electron/main.ts'),
        preload: path.resolve(__dirname, 'src/electron/preload.js'),
      },
      external: [
        // Node.js built-ins
        'stream',
        'path',
        'fs',
        'crypto',
        'buffer',
        'util',
        'events',
        'url',
        'assert',
        'os',
        'net',
        'http',
        'https',
        'zlib',
        'child_process',
        // Electron and Capacitor
        'electron',
        '@capacitor/core',
        '@capacitor-community/sqlite',
        '@capacitor-community/sqlite/electron',
        '@capacitor-community/sqlite/electron/dist/plugin',
        'better-sqlite3-multiple-ciphers',
        // HTTP clients
        'axios',
        'axios/dist/axios',
        'axios/dist/node/axios.cjs'
      ],
      output: {
        format: 'es',
        entryFileNames: '[name].mjs',
        assetFileNames: 'assets/[name].[ext]',
      },
    },
    target: 'node18',
    minify: false,
    sourcemap: true,
  },
  resolve: {
    alias: {
      '@': path.resolve(__dirname, 'src'),
      // Use Node.js version of axios in electron
      'axios': 'axios/dist/node/axios.cjs'
    },
  },
  optimizeDeps: {
    exclude: [
      'stream',
      'path',
      'fs',
      'crypto',
      'buffer',
      'util',
      'events',
      'url',
      'assert',
      'os',
      'net',
      'http',
      'https',
      'zlib',
      'child_process',
      'axios',
      'axios/dist/axios',
      'axios/dist/node/axios.cjs'
    ]
  },
  plugins: [
    {
      name: 'typescript-transform',
      transform(code: string, id: string) {
        if (id.endsWith('main.ts')) {
          return code.replace(
            /import\s*{\s*logger\s*}\s*from\s*['"]@\/utils\/logger['"];?/,
            `const logger = {
              log: (...args) => console.log(...args),
              error: (...args) => console.error(...args),
              info: (...args) => console.info(...args),
              warn: (...args) => console.warn(...args),
              debug: (...args) => console.debug(...args),
            };`
          );
        }
        return code;
      }
    }
  ],
  base: './',
  publicDir: 'public',
});