import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import { VitePWA, VitePWAOptions } from 'vite-plugin-pwa';
import VueI18nPlugin from '@intlify/unplugin-vue-i18n/vite';
import { fileURLToPath, URL } from 'node:url';
import path from 'node:path';

const pwaOptions: Partial<VitePWAOptions> = {
  registerType: 'autoUpdate',
  strategies: 'injectManifest',
  srcDir: 'src',
  filename: 'sw.ts',
  devOptions: {
    enabled: true,
    type: 'module',
    navigateFallback: 'index.html',
    suppressWarnings: true,
  },
  manifest: {
    name: 'mitlist',
    short_name: 'mitlist',
    description: 'mitlist pwa',
    theme_color: '#fff8f0',
    background_color: '#f3f3f3',
    display: 'standalone',
    orientation: 'portrait',
    icons: [
      { src: 'icons/icon-128x128.png', sizes: '128x128', type: 'image/png' },
      { src: 'icons/icon-192x192.png', sizes: '192x192', type: 'image/png' },
      { src: 'icons/icon-256x256.png', sizes: '256x256', type: 'image/png' },
      { src: 'icons/icon-384x384.png', sizes: '384x384', type: 'image/png' },
      { src: 'icons/icon-512x512.png', sizes: '512x512', type: 'image/png' },
    ],
  },
  injectManifest: {
    globPatterns: [
      '**/*.{js,css,html,ico,png,svg,woff2}',
      'offline.html',
    ],
    globIgnores: [
      '**/node_modules/**',
      '**/dist/**',
      'sw.js',
      'dev-sw.js',
      'index.html',
    ],
    maximumFileSizeToCacheInBytes: 15 * 1024 * 1024, // 5MB
  },
  workbox: {
    cleanupOutdatedCaches: true,
    sourcemap: true,
  },
};

export default defineConfig({
  plugins: [
    vue(),
    VitePWA(pwaOptions),
    VueI18nPlugin({
      include: [path.resolve(path.dirname(fileURLToPath(import.meta.url)), './src/i18n/**.json')],
      strictMessage: false,
      runtimeOnly: false,
      compositionOnly: false,
    }),
  ],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url)),
    },
  },
  define: {
    __PWA_FALLBACK_HTML__: JSON.stringify('/index.html'),
    __PWA_SERVICE_WORKER_REGEX__: JSON.stringify('^(sw|workbox)-.*\\.js$'),
    'process.env.MODE': JSON.stringify(process.env.NODE_ENV),
    'process.env.PROD': JSON.stringify(process.env.NODE_ENV === 'production'),
  },
  server: {
    open: true,
  },
});