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

export type CanonicalSurfaceElo = typeof schema.participantSurfaceElos.$inferSelect;
export type NewCanonicalSurfaceElo = typeof schema.participantSurfaceElos.$inferInsert;

export async function upsertCanonicalSurfaceElo(
  data: NewCanonicalSurfaceElo
): Promise<CanonicalSurfaceElo> {
  if (!data.participantId) {
    throw new Error("participantId is required");
  }

  const db = database();
  const [result] = await db
    .insert(schema.participantSurfaceElos)
    .values(data)
    .onConflictDoUpdate({
      target: [schema.participantSurfaceElos.participantId],
      set: {
        worldRanking: data.worldRanking,
        eloHard: data.eloHard,
        eloClay: data.eloClay,
        eloGrass: data.eloGrass,
        updatedAt: new Date(),
      },
    })
    .returning();
  return result;
}

export async function getCanonicalSurfaceElo(
  participantId: string
): Promise<CanonicalSurfaceElo | null> {
  const db = database();
  return await db.query.participantSurfaceElos.findFirst({
    where: eq(schema.participantSurfaceElos.participantId, participantId),
  }) ?? null;
}
