// @ts-check
import { defineConfig, mergeConfig } from "vite";
import { baseConfig } from "./vite.config.mjs";
import {
  apiServerBaseURL,
  apiServerPort,
} from "./configs/vars.mjs";

const config = defineConfig(async (configEnv) => {
  /**
   * @type {import("vite").UserConfig}
   */
  const targetBackend = `${apiServerBaseURL}${apiServerPort ? `:${apiServerPort}` : ''}`;
  const proxyConfig = {};
  if (targetBackend.includes("kemono.su")) {
    proxyConfig["/api/v1/creators"] = {
      target: "https://kemono.su", // target the base URL for the proxy
      changeOrigin: true,
      secure: true,
      rewrite: (path) => path.replace(/^\/api\/v1\/creators/, '/api/v1/creators.txt'),
    };
  }
  proxyConfig["/api"] = {
    target: targetBackend,
    changeOrigin: true,
    secure: true,
  };
  proxyConfig["/icons"] = {
    target: targetBackend,
    changeOrigin: true,
    secure: true,
  };
  proxyConfig["/banners"] = {
    target: targetBackend,
    changeOrigin: true,
    secure: true,
  };
  proxyConfig["/thumbnail"] = {
    target: targetBackend,
    changeOrigin: true,
    secure: true,
  };
  proxyConfig["/data"] = {
    target: targetBackend,
    changeOrigin: true,
    secure: true,
  };

  const devConfig = {
    server: {
      host: "0.0.0.0",
      port: 3450,
      strictPort: true,
      proxy: proxyConfig,
      allowedHosts: ["all"],
    },
  };

  const resolvedBase = await baseConfig(configEnv);
  const finalConfig = mergeConfig(resolvedBase, devConfig);

  return finalConfig;
});

export default config;