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

export async function initializeDraftTimers(seasonId: string, teams: { id: string }[], initialTime: number) {
  const timerData = teams.map((team) => ({
    seasonId,
    teamId: team.id,
    timeRemaining: initialTime,
  }));

  const db = database();
  await db.insert(schema.draftTimers).values(timerData);
}

export async function getTeamTimer(seasonId: string, teamId: string) {
  const db = database();
  const [timer] = await db
    .select()
    .from(schema.draftTimers)
    .where(and(eq(schema.draftTimers.seasonId, seasonId), eq(schema.draftTimers.teamId, teamId)));
  return timer;
}

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

export async function updateTeamTimer(seasonId: string, teamId: string, timeRemaining: number) {
  const db = database();
  const [timer] = await db
    .update(schema.draftTimers)
    .set({ timeRemaining, updatedAt: new Date() })
    .where(and(eq(schema.draftTimers.seasonId, seasonId), eq(schema.draftTimers.teamId, teamId)))
    .returning();
  return timer;
}

export async function deleteSeasonTimers(seasonId: string) {
  const db = database();
  await db.delete(schema.draftTimers).where(eq(schema.draftTimers.seasonId, seasonId));
}
