// @lovable.dev/vite-tanstack-config already includes the following — do NOT add them manually
// or the app will break with duplicate plugins:
//   - tanstackStart, viteReact, tailwindcss, tsConfigPaths, cloudflare (build-only),
//     componentTagger (dev-only), VITE_* env injection, @ path alias, React/TanStack dedupe,
//     error logger plugins, and sandbox detection (port/host/strictPort).
// You can pass additional config via defineConfig({ vite: { ... } }) if needed.
import { defineConfig } from "@lovable.dev/vite-tanstack-config";
import { writeFileSync, mkdirSync, readFileSync, existsSync } from "node:fs";
import { resolve } from "node:path";

// Keep BUILD_VERSION consistent across multiple vite.config.ts loads
// (dev server + worker) so __APP_VERSION__ in the client bundle matches
// the version.json served from /public. Otherwise the update banner
// shows forever because the two values are always different timestamps.
const VERSION_FILE = resolve("public/version.json");
let BUILD_VERSION = Date.now().toString();
if (process.env.NODE_ENV !== "production" && existsSync(VERSION_FILE)) {
  try {
    const existing = JSON.parse(readFileSync(VERSION_FILE, "utf8"));
    if (existing?.version) BUILD_VERSION = String(existing.version);
  } catch {
    // ignore — fall back to fresh timestamp
  }
}

export default defineConfig({
  vite: {
    define: {
      __APP_VERSION__: JSON.stringify(BUILD_VERSION),
    },
    plugins: [
      {
        name: "write-version-json",
        buildStart() {
          try {
            mkdirSync(resolve("public"), { recursive: true });
            writeFileSync(
              VERSION_FILE,
              JSON.stringify({ version: BUILD_VERSION }),
            );
          } catch {
            // ignore
          }
        },
      },
    ],
  },
});
