import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import { execSync } from 'child_process'
import fs from 'fs'
import path from 'path'

let gitSha = process.env.GIT_SHA
if (!gitSha) {
  try {
    gitSha = execSync('git rev-parse --short HEAD').toString().trim()
  } catch (e) {
    gitSha = 'dev'
  }
}

// https://vite.dev/config/
export default defineConfig({
  plugins: [
    react(),
    // Inject git SHA into service worker cache version so every deploy busts the SW cache
    {
      name: 'inject-sw-version',
      writeBundle() {
        const swPath = path.resolve(__dirname, 'dist/sw.js');
        if (!fs.existsSync(swPath)) return;
        let content = fs.readFileSync(swPath, 'utf-8');
        content = content.replace(
          /const CACHE_VERSION = '[^']*'/,
          `const CACHE_VERSION = 'dumpster-${gitSha}'`
        );
        fs.writeFileSync(swPath, content);
      },
    },
  ],
  define: {
    __APP_VERSION__: JSON.stringify(`v${gitSha}`),
  },
  server: {
    host: '0.0.0.0',
    proxy: {
      '/api': {
        target: 'http://localhost:8080',
        changeOrigin: true,
      },
      '/ws': {
        target: 'ws://localhost:8080',
        ws: true,
      },
    },
  },
})
