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

export default defineConfig({
  // 仅在使用 `cd frontend && npm run dev` 时需要：另开终端运行 `wrangler dev`，API 会转到 8787
  server: {
    proxy: {
      '/api': {
        target: 'http://127.0.0.1:8787',
        changeOrigin: true,
      },
    },
  },
  plugins: [
    react(),
    VitePWA({
      registerType: 'autoUpdate',
      includeAssets: ['favicon.ico', 'logo.png'],
      manifest: {
        name: 'Sprout2FA',
        short_name: 'Sprout2FA',
        description: '网页版 2FA / TOTP 管理器',
        theme_color: '#14532d',
        background_color: '#ecfdf5',
        display: 'standalone',
        orientation: 'portrait-primary',
        start_url: '/',
        scope: '/',
        icons: [
          {
            src: '/logo.png',
            sizes: '512x512',
            type: 'image/png',
            purpose: 'any maskable',
          },
        ],
      },
      workbox: {
        // logo.png 可能较大，不加入 SW 预缓存，避免超过默认 2MiB 限制；页面仍正常引用 /logo.png
        globPatterns: ['**/*.{js,css,html,svg,ico,woff2}'],
        globIgnores: ['**/logo.png'],
        runtimeCaching: [
          {
            urlPattern: ({ url }: { url: URL }) => url.pathname.startsWith('/api'),
            handler: 'NetworkOnly',
          },
        ],
      },
    }),
  ],
  build: {
    outDir: 'dist',
    emptyOutDir: true,
  },
});
