import type { NextConfig } from "next";

function firstDefined(...values: Array<string | undefined>): string | undefined {
  return values.find((value) => typeof value === "string" && value.length > 0);
}

function resolveClientEnv(): Record<string, string> {
  const aliasMap: Record<string, string | undefined> = {
    NEXT_PUBLIC_ATHENA_BASE_URL: firstDefined(
      process.env.NEXT_PUBLIC_ATHENA_BASE_URL,
      process.env.ATHENA_BASE_URL,
      process.env.BASE_URL,
    ),
    NEXT_PUBLIC_ATHENA_API_KEY: firstDefined(
      process.env.NEXT_PUBLIC_ATHENA_API_KEY,
      process.env.NEXT_PUBLIC_ATHENA_P12_KEY,
      process.env.ATHENA_API_KEY,
      process.env.ATHENA_P12_KEY,
      process.env.ATHENA_KEY_12,
      process.env.API_KEY,
    ),
    NEXT_PUBLIC_ATHENA_P12_KEY: firstDefined(
      process.env.NEXT_PUBLIC_ATHENA_P12_KEY,
      process.env.NEXT_PUBLIC_ATHENA_API_KEY,
      process.env.ATHENA_P12_KEY,
      process.env.ATHENA_API_KEY,
      process.env.ATHENA_KEY_12,
      process.env.API_KEY,
    ),
    NEXT_PUBLIC_ATHENA_PG_DUMP_PATH: firstDefined(
      process.env.NEXT_PUBLIC_ATHENA_PG_DUMP_PATH,
      process.env.ATHENA_PG_DUMP_PATH,
      process.env.PG_DUMP_PATH,
    ),
    NEXT_PUBLIC_ATHENA_PG_RESTORE_PATH: firstDefined(
      process.env.NEXT_PUBLIC_ATHENA_PG_RESTORE_PATH,
      process.env.ATHENA_PG_RESTORE_PATH,
      process.env.PG_RESTORE_PATH,
    ),
    NEXT_PUBLIC_ATHENA_CLIENT: firstDefined(
      process.env.NEXT_PUBLIC_ATHENA_CLIENT,
      process.env.ATHENA_CLIENT,
      process.env.CLIENT,
    ),
    NEXT_PUBLIC_ATHENA_DB_NAME: firstDefined(
      process.env.NEXT_PUBLIC_ATHENA_DB_NAME,
      process.env.ATHENA_DB_NAME,
      process.env.DB_NAME,
    ),
    NEXT_PUBLIC_ATHENA_USER_ID: firstDefined(
      process.env.NEXT_PUBLIC_ATHENA_USER_ID,
      process.env.ATHENA_USER_ID,
      process.env.USER_ID,
    ),
    NEXT_PUBLIC_ATHENA_COMPANY_ID: firstDefined(
      process.env.NEXT_PUBLIC_ATHENA_COMPANY_ID,
      process.env.ATHENA_COMPANY_ID,
      process.env.COMPANY_ID,
    ),
    NEXT_PUBLIC_ATHENA_ORGANIZATION_ID: firstDefined(
      process.env.NEXT_PUBLIC_ATHENA_ORGANIZATION_ID,
      process.env.ATHENA_ORGANIZATION_ID,
      process.env.ORGANIZATION_ID,
    ),
  };

  return Object.fromEntries(
    Object.entries(aliasMap).filter(([, value]) => typeof value === "string"),
  ) as Record<string, string>;
}

const nextConfig: NextConfig = {
  output: "export",
  transpilePackages: ["@xylex-group/auth-ui"],
  env: resolveClientEnv(),
};

export default nextConfig;
