import { eq } from "drizzle-orm"; import { database } from "~/database/context"; import * as schema from "~/database/schema"; export type Participant = typeof schema.participants.$inferSelect; export type NewParticipant = typeof schema.participants.$inferInsert; export async function createParticipant(data: NewParticipant): Promise { const db = database(); const [participant] = await db .insert(schema.participants) .values(data) .returning(); return participant; } export async function createManyParticipants(data: NewParticipant[]): Promise { const db = database(); return await db .insert(schema.participants) .values(data) .returning(); } export async function findParticipantById(id: string): Promise { const db = database(); return await db.query.participants.findFirst({ where: eq(schema.participants.id, id), with: { sportsSeason: { with: { sport: true, }, }, }, }); } export async function findParticipantsBySportsSeasonId(sportsSeasonId: string): Promise { const db = database(); return await db.query.participants.findMany({ where: eq(schema.participants.sportsSeasonId, sportsSeasonId), orderBy: (participants, { asc }) => [asc(participants.name)], }); } export async function findParticipantsByExternalId( externalId: string ): Promise { const db = database(); return await db.query.participants.findMany({ where: eq(schema.participants.externalId, externalId), with: { sportsSeason: { with: { sport: true, }, }, }, }); } export async function updateParticipant( id: string, data: Partial ): Promise { const db = database(); const [participant] = await db .update(schema.participants) .set({ ...data, updatedAt: new Date() }) .where(eq(schema.participants.id, id)) .returning(); return participant; } export async function deleteParticipant(id: string): Promise { const db = database(); await db.delete(schema.participants).where(eq(schema.participants.id, id)); } export async function copyParticipantsFromSeason( sourceSportsSeasonId: string, targetSportsSeasonId: string ): Promise { // Get all participants from source season const sourceParticipants = await findParticipantsBySportsSeasonId(sourceSportsSeasonId); // Insert them into the target season if (sourceParticipants.length === 0) { return []; } return await createManyParticipants( sourceParticipants.map((p) => ({ sportsSeasonId: targetSportsSeasonId, name: p.name, shortName: p.shortName, externalId: p.externalId, expectedValue: p.expectedValue, })) ); }