import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import { fileURLToPath, URL } from 'node:url';

const apiTarget = process.env.PIG_API_TARGET ?? 'http://localhost:8920';

export default defineConfig({
  plugins: [react()],
  resolve: {
    alias: { '@': fileURLToPath(new URL('./src', import.meta.url)) },
  },
  server: {
    // Both are overridable so a second checkout (a worktree, a review branch)
    // can run its own API and web server without colliding with the first.
    port: Number(process.env.PIG_WEB_PORT ?? 5173),
    // Proxy in development so the browser sees one origin, matching how
    // production serves the API and the app together. Auth sessions are
    // per-origin, so a split origin in dev but not prod hides real bugs.
    /*
     * `/media` is proxied as well as `/api`, because Learn videos PIG hosts
     * itself are served from the API on a non-/api path. Without this entry
     * Vite answers the <video> request with index.html and the player shows a
     * black box with working controls and no error — the same silent
     * 200-text/html failure the API guards against for its own routes.
     */
    proxy: {
      '/api': { target: apiTarget, changeOrigin: true },
      '/media': { target: apiTarget, changeOrigin: true },
    },
  },
  build: {
    outDir: 'dist',
    sourcemap: true,
    rollupOptions: {
      output: {
        /*
         * Split the vendor code that changes rarely from the app code that
         * changes constantly, so a deploy invalidates only the small chunk.
         * This matters on mobile: the auth client alone is a large download,
         * and re-fetching it on every deploy over a cellular connection is
         * exactly the cost worth avoiding.
         */
        manualChunks: {
          react: ['react', 'react-dom', 'react-router-dom'],
          supabase: ['@supabase/supabase-js'],
          query: ['@tanstack/react-query'],
          /*
           * Named explicitly, or the object form of `manualChunks` hoists the
           * markdown parser into the entry chunk even though the only importers
           * are lazy routes — measured at 327.70 kB gzip entry with it hoisted
           * against 314 kB without. As its own chunk it is fetched when a
           * Motion page is opened and never on any other route.
           */
          markdown: ['react-markdown', 'remark-gfm'],
        },
      },
    },
  },
});
