import { eq, inArray, and } from "drizzle-orm";
import { database } from "~/database/context";
import * as schema from "~/database/schema";

export type LinkedAccount = {
  id: string;
  providerId: string;
};

export async function findLinkedAccountsByUserId(userId: string): Promise<LinkedAccount[]> {
  const db = database();
  return db
    .select({ id: schema.accounts.id, providerId: schema.accounts.providerId })
    .from(schema.accounts)
    .where(eq(schema.accounts.userId, userId));
}

export async function findDiscordIdsByUserIds(userIds: string[]): Promise<Map<string, string>> {
  if (userIds.length === 0) return new Map();
  const db = database();
  const rows = await db
    .select({ userId: schema.accounts.userId, accountId: schema.accounts.accountId })
    .from(schema.accounts)
    .where(and(inArray(schema.accounts.userId, userIds), eq(schema.accounts.providerId, "discord")));
  return new Map(rows.map((r) => [r.userId, r.accountId]));
}
