import { defineConfig, loadEnv } from "vite";
import react from "@vitejs/plugin-react";

export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd(), "");
  const apiProxyTarget = env.DEV_API_PROXY_TARGET || "http://127.0.0.1:8080";
  // Uploaded assets (thumbnails etc.) are served from the site root, NOT under
  // the API's /apnew prefix. Proxy /uploads to the origin root so relative
  // thumbnailUrls like "/uploads/thumb52-….jpg" resolve to a real image in dev
  // instead of falling through to the SPA's index.html.
  const uploadsProxyTarget = (() => {
    try {
      return new URL(apiProxyTarget).origin;
    } catch {
      return apiProxyTarget;
    }
  })();

  return {
    plugins: [react()],
    build: {
      rollupOptions: {
        output: {
          // Entry script at site root (/index-[hash].js); lazy chunks + CSS stay under /assets/.
          entryFileNames: "[name]-[hash].js",
          chunkFileNames: "assets/[name]-[hash].js",
          assetFileNames: "assets/[name]-[hash][extname]",
        },
      },
    },
    server: {
      port: 5173,
      proxy: {
        "/apnew/api": {
          target: apiProxyTarget,
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/apnew/, ""),
        },
        "/api": { target: apiProxyTarget, changeOrigin: true },
        "/uploads": { target: uploadsProxyTarget, changeOrigin: true },
      },
    },
  };
});
