/**
 * Vite Configuration
 *
 * Configures:
 * - Cross-origin isolation headers (required for OPFS/SQLite)
 * - Worker bundling
 */

import { defineConfig } from 'vite';

export default defineConfig({
  // Development server configuration
  server: {
    headers: {
      // Required for OPFS (Origin Private File System) access
      'Cross-Origin-Opener-Policy': 'same-origin',
      'Cross-Origin-Embedder-Policy': 'require-corp',
    },
  },

  // Preview server (npm run preview) configuration
  preview: {
    headers: {
      'Cross-Origin-Opener-Policy': 'same-origin',
      'Cross-Origin-Embedder-Policy': 'require-corp',
    },
  },

  // Build configuration
  build: {
    // Generate source maps for debugging
    sourcemap: true,

    // Target modern browsers that support OPFS
    target: 'esnext',

    // Raise the chunk-size warning threshold.
    // Rationale: the two largest chunks are unavoidable —
    //   • openlayers (~535 kB / ~152 kB gzipped) — the OL library itself,
    //     used app-wide; further splitting just creates more HTTP round-trips
    //   • sqlite3.wasm (~856 kB) — a runtime WASM binary, not a JS chunk;
    //     code-splitting does not apply
    // 900 kB silences the noise without hiding genuine regressions.
    chunkSizeWarningLimit: 900,

    rollupOptions: {
      output: {
        manualChunks(id) {
          if (id.includes('node_modules/ol/')) return 'openlayers';
          if (id.includes('node_modules/ol-ext/')) return 'ol-ext';
          if (id.includes('node_modules/bootstrap/')) return 'bootstrap';
          // shpjs (+ its jszip dependency) — dynamically imported at runtime,
          // so this chunk is only fetched when the user imports a shapefile.
          if (id.includes('node_modules/shpjs/') || id.includes('node_modules/jszip/')) return 'shpjs';
          if (id.includes('node_modules/jspdf')) return 'jspdf';
        },
      },
    },
  },

  // Worker configuration
  worker: {
    format: 'es',
  },

  // Dependency optimization
  optimizeDeps: {
    exclude: ['sqlocal'],
  },
});
