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

export default defineConfig({
  plugins: [
    react(),
    VitePWA({
      registerType: "autoUpdate",
      includeAssets: ["favicon.ico", "apple-touch-icon.png"],
      manifest: {
        name: "Skori — Scores de jeux de société",
        short_name: "Skori",
        description:
          "Application Web de gestion des scores pour jeux de société",
        lang: "fr",
        start_url: "/",
        scope: "/",
        display: "standalone",
        orientation: "portrait",
        theme_color: "#0f766e",
        background_color: "#0b1120",
        categories: ["games", "utilities"],
        icons: [
          {
            src: "pwa-192x192.png",
            sizes: "192x192",
            type: "image/png",
          },
          {
            src: "pwa-512x512.png",
            sizes: "512x512",
            type: "image/png",
          },
          {
            src: "pwa-maskable-512x512.png",
            sizes: "512x512",
            type: "image/png",
            purpose: "maskable",
          },
        ],
      },
      workbox: {
        // Précache le shell de l'app + les logos/bannières (légers, en webp)
        globPatterns: ["**/*.{js,css,html,ico,png,svg,webp,woff2}"],
        // Les PDF de règles (jusqu'à 12 Mo) ne sont PAS précachés :
        // ils sont mis en cache à la demande, à la première consultation.
        runtimeCaching: [
          {
            urlPattern: /\/games-assets\/.*\.pdf$/,
            handler: "CacheFirst",
            options: {
              cacheName: "rules-pdf",
              expiration: {
                maxEntries: 10,
                maxAgeSeconds: 60 * 60 * 24 * 90, // 90 jours
              },
              cacheableResponse: { statuses: [0, 200] },
            },
          },
        ],
        navigateFallback: "/index.html",
        // Never let the SPA fallback swallow API calls.
        navigateFallbackDenylist: [/^\/api/],
        cleanupOutdatedCaches: true,
      },
    }),
  ],
  resolve: {
    alias: {
      "@": path.resolve(__dirname, "./src"),
    },
  },
  server: {
    // Dev: forward /api to the backend so the browser sees a single origin
    // (required for the httpOnly refresh cookie to work end-to-end).
    proxy: {
      "/api": {
        target: "http://localhost:3001",
        changeOrigin: true,
      },
    },
  },
});
