import { eq, and, asc } from 'drizzle-orm';
import { db } from '../db';
import { soulseekFavorites } from '../schema';

/** A user's favourited Soulseek peers, alphabetical (the order the UI lists them in). */
export async function getSoulseekFavorites(userId: number): Promise<string[]> {
  const rows = await db
    .select({ username: soulseekFavorites.username })
    .from(soulseekFavorites)
    .where(eq(soulseekFavorites.userId, userId))
    .orderBy(asc(soulseekFavorites.username));
  return rows.map((r) => r.username);
}

/** Add a favourite (idempotent — a repeat add is a no-op via the unique constraint). */
export async function addSoulseekFavorite(userId: number, username: string): Promise<void> {
  await db.insert(soulseekFavorites).values({ userId, username }).onConflictDoNothing();
}

/** Remove a favourite (no-op if it wasn't set). */
export async function removeSoulseekFavorite(userId: number, username: string): Promise<void> {
  await db
    .delete(soulseekFavorites)
    .where(and(eq(soulseekFavorites.userId, userId), eq(soulseekFavorites.username, username)));
}
