import { eq, and, asc } from "drizzle-orm"; import { database } from "~/database/context"; import * as schema from "~/database/schema"; export type TournamentResult = typeof schema.tournamentResults.$inferSelect; export type NewTournamentResult = typeof schema.tournamentResults.$inferInsert; export async function upsertTournamentResult( data: NewTournamentResult ): Promise { if (!data.tournamentId || !data.participantId) { throw new Error("tournamentId and participantId are required"); } const db = database(); const [result] = await db .insert(schema.tournamentResults) .values(data) .onConflictDoUpdate({ target: [ schema.tournamentResults.tournamentId, schema.tournamentResults.participantId, ], set: { placement: data.placement, rawScore: data.rawScore, updatedAt: new Date(), }, }) .returning(); return result; } export async function getTournamentResults( tournamentId: string ): Promise { const db = database(); return await db .select() .from(schema.tournamentResults) .where(eq(schema.tournamentResults.tournamentId, tournamentId)) .orderBy(asc(schema.tournamentResults.placement)); } export async function getTournamentResultByParticipant( tournamentId: string, participantId: string ): Promise { const db = database(); const results = await db .select() .from(schema.tournamentResults) .where( and( eq(schema.tournamentResults.tournamentId, tournamentId), eq(schema.tournamentResults.participantId, participantId) ) ) .limit(1); return results[0] ?? null; }