import { inArray } from 'drizzle-orm';
import { users } from '@/db/schema';
import { db } from '@/lib/db';

export type UserDisplayRecord = {
  id: string;
  name: string | null;
  email: string;
  displayName: string;
};

function resolveDisplayName(row: { id: string; name: string | null; email: string }) {
  const name = row.name?.trim();

  if (name) {
    return name;
  }

  const email = row.email.trim();
  if (email) {
    return email;
  }

  return row.id;
}

export async function resolveUserDisplays(userIds: Array<string | null | undefined>) {
  const uniqueIds = [...new Set(userIds.filter((value): value is string => Boolean(value)))];

  if (!uniqueIds.length) {
    return new Map<string, UserDisplayRecord>();
  }

  const rows = await db
    .select({
      id: users.id,
      name: users.name,
      email: users.email
    })
    .from(users)
    .where(inArray(users.id, uniqueIds));

  return new Map(
    rows.map((row) => [
      row.id,
      {
        ...row,
        displayName: resolveDisplayName(row)
      }
    ])
  );
}
