import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import { VitePWA } from 'vite-plugin-pwa';

export default defineConfig({
  plugins: [
    react(),
    VitePWA({
      registerType: 'autoUpdate',
      includeAssets: ['favicon.ico', 'apple-touch-icon.png', 'mask-icon.svg'],
      manifest: {
        name: 'NextGen School',
        short_name: 'NextGen',
        description: 'Modern School Management System',
        theme_color: '#2563eb',
        background_color: '#ffffff',
        display: 'standalone',
        start_url: '/',
        scope: '/',
        icons: [
          {
            src: 'pwa-192x192.png',
            sizes: '192x192',
            type: 'image/png'
          },
          {
            src: 'pwa-512x512.png',
            sizes: '512x512',
            type: 'image/png'
          },
          {
            src: 'pwa-512x512.png',
            sizes: '512x512',
            type: 'image/png',
            purpose: 'any maskable'
          }
        ]
      },
      workbox: {
        globPatterns: ['**/*.{js,css,html,ico,png,svg,wasm,webmanifest}'],
        maximumFileSizeToCacheInBytes: 5 * 1024 * 1024, // 5MB
        runtimeCaching: [
          {
            urlPattern: /^https:\/\/fonts\.googleapis\.com\/.*/i,
            handler: 'CacheFirst',
            options: {
              cacheName: 'google-fonts-cache',
              expiration: {
                maxEntries: 10,
                maxAgeSeconds: 60 * 60 * 24 * 365
              }
            }
          },
          // Student Medical — kitchen tablet + nurse reads must work offline.
          // NetworkFirst: try the hub (so edits and writes hit the server when
          // it's reachable); fall back to the SW cache for reads when it's not.
          // The api.ts response interceptor also routes network errors to the
          // local SQLite WASM DB, so this is the second layer of defence.
          {
            urlPattern: /\/api\/medical\/(dining|class)\/.*/i,
            handler: 'NetworkFirst',
            options: {
              cacheName: 'medical-roster-cache',
              networkTimeoutSeconds: 5,
              expiration: {
                maxEntries: 100,
                maxAgeSeconds: 60 * 60 * 24 * 7
              }
            }
          },
          {
            urlPattern: /\/api\/medical\/(profiles|logs|history)\/.*/i,
            handler: 'NetworkFirst',
            options: {
              cacheName: 'medical-record-cache',
              networkTimeoutSeconds: 5,
              expiration: {
                maxEntries: 200,
                maxAgeSeconds: 60 * 60 * 24
              }
            }
          }
        ]
      }
    })
  ],
  worker: {
    format: 'es',
  },
  optimizeDeps: {
    exclude: ['@sqlite.org/sqlite-wasm']
  },
  server: {
    port: Number(process.env.VITE_PORT) || 3000,
    strictPort: true,
    proxy: {
      '/api': process.env.VITE_API_TARGET || 'http://127.0.0.1:3001',
      '/uploads': process.env.VITE_API_TARGET || 'http://127.0.0.1:3001',
      // PR 3 §13 follow-up — forward WebSocket upgrades so the realtime
      // store can talk to the server's wsHub during dev. The server's
      // wsHub also handles Sec-WebSocket-Protocol auth headers; vite's
      // default proxy preserves those for WS upgrades.
      '/ws': {
        target: process.env.VITE_WS_TARGET || 'ws://127.0.0.1:3001',
        ws: true,
        changeOrigin: true,
        rewriteWsOrigin: true,
      },
      '/socket': {
        target: process.env.VITE_WS_TARGET || 'ws://127.0.0.1:3001',
        ws: true,
        changeOrigin: true,
      },
    },
    headers: {
      'Cross-Origin-Opener-Policy': 'same-origin',
      'Cross-Origin-Embedder-Policy': 'require-corp',
      'Cross-Origin-Resource-Policy': 'cross-origin',
    }
  }
});