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

export async function addToWatchlist(data: {
  seasonId: string;
  teamId: string;
  participantId: string;
}) {
  const db = database();
  const [item] = await db.insert(schema.watchlist).values(data).returning();
  return item;
}

export async function removeFromWatchlist(data: {
  seasonId: string;
  teamId: string;
  participantId: string;
}) {
  const db = database();
  await db
    .delete(schema.watchlist)
    .where(
      and(
        eq(schema.watchlist.seasonId, data.seasonId),
        eq(schema.watchlist.teamId, data.teamId),
        eq(schema.watchlist.participantId, data.participantId)
      )
    );
}

export async function getTeamWatchlist(teamId: string, seasonId: string) {
  const db = database();
  return await db
    .select()
    .from(schema.watchlist)
    .where(
      and(
        eq(schema.watchlist.teamId, teamId),
        eq(schema.watchlist.seasonId, seasonId)
      )
    );
}

export async function isOnWatchlist(
  teamId: string,
  participantId: string
): Promise<boolean> {
  const db = database();
  const existing = await db.query.watchlist.findFirst({
    where: and(
      eq(schema.watchlist.teamId, teamId),
      eq(schema.watchlist.participantId, participantId)
    ),
  });
  return !!existing;
}
