import type { SupabaseClient } from "@supabase/supabase-js";

export async function buildAuthorUsernameMap(
  supabase: SupabaseClient,
): Promise<Record<string, string>> {
  const { data } = await supabase
    .from("forum_user_profiles")
    .select("username, display_name");
  const map: Record<string, string> = {};
  for (const row of data || []) {
    if (row.display_name && row.username) {
      map[row.display_name] = row.username;
    }
  }
  return map;
}

export function attachAuthorUsernames<
  T extends { author_name?: string | null },
>(rows: T[] | null | undefined, map: Record<string, string>) {
  return (rows || []).map((row) => ({
    ...row,
    author_username: row.author_name ? map[row.author_name] || null : null,
  }));
}