import { createRequire } from "node:module";
import path from "node:path";
import { fileURLToPath } from "node:url";
import react from "@vitejs/plugin-react";
import { defineConfig, type UserConfig } from "vite";

const require = createRequire(import.meta.url);
const commonWorkspaceDir = path.resolve(
  path.dirname(fileURLToPath(import.meta.url)),
  "..",
);
const appWorkspaceDir = path.resolve(process.cwd());
const reactPackageDir = path.dirname(require.resolve("react/package.json"));
const reactDomPackageDir = path.dirname(
  require.resolve("react-dom/package.json"),
);

export const commonViteConfig: UserConfig = {
  plugins: [react()],
  resolve: {
    // 공용 패키지에서 hook를 쓰는 컴포넌트를 가져올 때 React가 중복 로드되면
    // dispatcher가 분리되어 useState/useEffect가 런타임에 깨질 수 있습니다.
    alias: {
      react: reactPackageDir,
      "react-dom": reactDomPackageDir,
    },
    dedupe: ["react", "react-dom"],
  },
  build: {
    emptyOutDir: true,
  },
  server: {
    fs: {
      allow: [appWorkspaceDir, commonWorkspaceDir, "/workspace/common"],
    },
  },
};

export function hostFromUrl(value: string | undefined) {
  if (!value) return undefined;
  try {
    return new URL(value).hostname;
  } catch {
    return value;
  }
}

export function getAllowedHosts(
  defaultHosts: string[],
  envUrl?: string,
  envAllowedHosts?: string,
) {
  return Array.from(
    new Set(
      [
        ...defaultHosts,
        hostFromUrl(envUrl),
        ...(envAllowedHosts ?? "")
          .split(",")
          .map((host) => host.trim())
          .filter(Boolean),
      ].filter((host): host is string => Boolean(host)),
    ),
  );
}

export default defineConfig(commonViteConfig);
