const { defineConfig } = require('vite')
const vue = require('@vitejs/plugin-vue')
const path = require('path')

// Import conditionnel du plugin PWA
let VitePWA = null
try {
  VitePWA = require('vite-plugin-pwa').VitePWA
} catch (e) {
  console.warn('⚠️  vite-plugin-pwa n\'est pas installé. La fonctionnalité PWA sera désactivée.')
  console.warn('   Installez-le avec: npm install --save-dev vite-plugin-pwa')
}

// Configuration par environnement
const getEnvironmentConfig = (mode) => {
  const configs = {
    local: {
      server: {
        host: '0.0.0.0',
        port: 5173,
        allowedHosts: ['localhost', '127.0.0.1'],
        proxy: {
          '/api': {
            target: 'http://localhost:8000',
            changeOrigin: true,
            secure: false
          },
          '/uploads': {
            target: 'http://localhost:8000',
            changeOrigin: true,
            secure: false
          }
        }
      },
      define: {
        __ENVIRONMENT__: '"local"'
      }
    },
    development: {
      server: {
        host: '0.0.0.0',
        port: 5173,
        allowedHosts: ['dev.lediscord.com', 'localhost'],
        // Pas de proxy en développement car l'API est externe (https://api-dev.lediscord.com)
        // Le proxy n'est nécessaire que pour l'environnement local
      },
      define: {
        __ENVIRONMENT__: '"development"'
      }
    },
    production: {
      server: {
        host: '0.0.0.0',
        port: 5173,
        allowedHosts: ['lediscord.com', 'www.lediscord.com'],
        proxy: {
          '/api': {
            target: 'https://api.lediscord.com',
            changeOrigin: true,
            secure: true
          },
          '/uploads': {
            target: 'https://api.lediscord.com',
            changeOrigin: true,
            secure: true
          }
        }
      },
      define: {
        __ENVIRONMENT__: '"production"'
      }
    }
  }
  
  return configs[mode] || configs.local
}

module.exports = defineConfig(({ command, mode }) => {
  // Détecter l'environnement
  const env = process.env.NODE_ENV || mode || 'local'
  const envConfig = getEnvironmentConfig(env)
  
  console.log(`🚀 Configuration Vite pour l'environnement: ${env.toUpperCase()}`)
  console.log(`🔧 Variables d'environnement:`, {
    NODE_ENV: process.env.NODE_ENV,
    VITE_ENVIRONMENT: process.env.VITE_ENVIRONMENT,
    VITE_API_URL: process.env.VITE_API_URL,
    VITE_APP_URL: process.env.VITE_APP_URL
  })
  
  const plugins = [vue()]
  
  // Ajouter le plugin PWA seulement s'il est installé
  if (VitePWA) {
    plugins.push(VitePWA({
        registerType: 'autoUpdate',
        includeAssets: ['favicon.ico', 'logo_lediscord.png'],
        manifest: {
          name: 'LeDiscord - Notre espace',
          short_name: 'LeDiscord',
          description: 'Plateforme communautaire LeDiscord',
          theme_color: '#6366f1',
          background_color: '#ffffff',
          display: 'standalone',
          orientation: 'portrait-primary',
          scope: '/',
          start_url: '/',
          icons: [
            {
              src: '/icon-72x72.png',
              sizes: '72x72',
              type: 'image/png',
              purpose: 'any maskable'
            },
            {
              src: '/icon-96x96.png',
              sizes: '96x96',
              type: 'image/png',
              purpose: 'any maskable'
            },
            {
              src: '/icon-128x128.png',
              sizes: '128x128',
              type: 'image/png',
              purpose: 'any maskable'
            },
            {
              src: '/icon-144x144.png',
              sizes: '144x144',
              type: 'image/png',
              purpose: 'any maskable'
            },
            {
              src: '/icon-152x152.png',
              sizes: '152x152',
              type: 'image/png',
              purpose: 'any maskable'
            },
            {
              src: '/icon-192x192.png',
              sizes: '192x192',
              type: 'image/png',
              purpose: 'any maskable'
            },
            {
              src: '/icon-384x384.png',
              sizes: '384x384',
              type: 'image/png',
              purpose: 'any maskable'
            },
            {
              src: '/icon-512x512.png',
              sizes: '512x512',
              type: 'image/png',
              purpose: 'any maskable'
            }
          ],
          shortcuts: [
            {
              name: 'Vlogs',
              short_name: 'Vlogs',
              description: 'Voir les vlogs',
              url: '/vlogs',
              icons: [{ src: '/icon-96x96.png', sizes: '96x96' }]
            },
            {
              name: 'Albums',
              short_name: 'Albums',
              description: 'Voir les albums',
              url: '/albums',
              icons: [{ src: '/icon-96x96.png', sizes: '96x96' }]
            }
          ],
          categories: ['social', 'entertainment']
        },
        workbox: {
          globPatterns: ['**/*.{js,css,html,ico,png,svg,jpg,jpeg,webp,mp4}'],
          // Notifications push
          navigateFallback: null,
          skipWaiting: true,
          clientsClaim: true,
          runtimeCaching: [
            {
              urlPattern: /^https:\/\/fonts\.googleapis\.com\/.*/i,
              handler: 'CacheFirst',
              options: {
                cacheName: 'google-fonts-cache',
                expiration: {
                  maxEntries: 10,
                  maxAgeSeconds: 60 * 60 * 24 * 365 // 1 year
                },
                cacheableResponse: {
                  statuses: [0, 200]
                }
              }
            },
            {
              urlPattern: /^https:\/\/fonts\.gstatic\.com\/.*/i,
              handler: 'CacheFirst',
              options: {
                cacheName: 'gstatic-fonts-cache',
                expiration: {
                  maxEntries: 10,
                  maxAgeSeconds: 60 * 60 * 24 * 365 // 1 year
                },
                cacheableResponse: {
                  statuses: [0, 200]
                }
              }
            },
            {
              urlPattern: /^https?:\/\/.*\/api\/.*/i,
              handler: 'NetworkFirst',
              options: {
                cacheName: 'api-cache',
                expiration: {
                  maxEntries: 50,
                  maxAgeSeconds: 60 * 5 // 5 minutes
                },
                networkTimeoutSeconds: 10
              }
            },
            {
              urlPattern: /^https?:\/\/.*\/uploads\/.*/i,
              handler: 'CacheFirst',
              options: {
                cacheName: 'uploads-cache',
                expiration: {
                  maxEntries: 100,
                  maxAgeSeconds: 60 * 60 * 24 * 7 // 7 days
                },
                cacheableResponse: {
                  statuses: [0, 200]
                }
              }
            }
          ]
        },
        devOptions: {
          enabled: true,
          type: 'module'
        }
      }))
  }
  
  return {
    plugins,
    resolve: {
      alias: {
        '@': path.resolve(__dirname, './src')
      }
    },
    
    // Configuration du serveur selon l'environnement
    server: envConfig.server,
    
    // Configuration pour la production
    build: {
      rollupOptions: {
        output: {
          manualChunks: {
            vendor: ['vue', 'vue-router', 'pinia'],
            utils: ['axios', 'date-fns']
          }
        }
      },
      // Optimisations de production
      minify: env === 'production' ? 'terser' : false,
      sourcemap: env !== 'production',
      // Variables d'environnement
      define: envConfig.define
    },
    
    // Configuration des variables d'environnement
    define: {
      ...envConfig.define,
      __BUILD_TIME__: JSON.stringify(new Date().toISOString()),
      // Forcer les variables d'environnement
      'import.meta.env.VITE_ENVIRONMENT': JSON.stringify(process.env.VITE_ENVIRONMENT || env),
      'import.meta.env.VITE_API_URL': JSON.stringify(process.env.VITE_API_URL),
      'import.meta.env.VITE_APP_URL': JSON.stringify(process.env.VITE_APP_URL)
    },
    
    // Optimisations selon l'environnement
    optimizeDeps: {
      include: ['vue', 'vue-router', 'pinia', 'axios']
    },
    
    // Configuration des assets
    assetsInclude: ['**/*.png', '**/*.jpg', '**/*.jpeg', '**/*.gif', '**/*.svg', '**/*.mp4', '**/*.webm'],
    
    // Configuration du mode
    mode: env === 'production' ? 'production' : 'development'
  }
})
