import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'
import fs from 'fs'
import pkg from './package.json'

function swBuildVersionPlugin() {
  return {
    name: 'sw-build-version',
    closeBundle() {
      const manifestPath = './public/build/.vite/manifest.json';
      if (!fs.existsSync(manifestPath)) return;
      const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
      const entry = Object.values(manifest).find(e => e.isEntry);
      if (!entry) return;
      const version = entry.file.replace(/^assets\//, '').replace(/\.[^.]+$/, '');
      const swPath = './public/sw.js';
      const sw = fs.readFileSync(swPath, 'utf8');
      fs.writeFileSync(swPath, sw.replace(/const BUILD_VERSION = '[^']*';/, `const BUILD_VERSION = '${version}';`));
    }
  };
}

export default defineConfig({
    plugins: [vue(), swBuildVersionPlugin()],
    server: {
        host: true,
        port: 5173
    },
    base: '/build/',
    build: {
        outDir: 'public/build',
        emptyOutDir: true,
        manifest: true,
        rollupOptions: {
            input: path.resolve(__dirname, 'resources/js/app.js'),
            output: {
                manualChunks: {
                    // Core vendor libs — cached independently for long-term browser caching
                    vendor: ['vue', 'pinia', 'axios'],
                },
            },
        },
    },
    publicDir: 'public',
    resolve: {
        alias: {
            '@': path.resolve(__dirname, 'resources/js') 
        }
    },
    define: {
        '__APP_VERSION__': JSON.stringify(pkg.version),
        '__BUILD_ID__': JSON.stringify(new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '').slice(0, 16))
    }
})
