import { usePrisma } from "../utils/prisma";

/**
 * Returns the active CooldownRequest for a user:
 * not resolved, not cancelled, cooldownEndsAt in the future.
 * (Expired but not yet resolved entries are also returned so the caller can resolve them.)
 */
export async function getActiveCooldown(userId: string) {
  const db = usePrisma();
  return db.cooldownRequest.findFirst({
    where: {
      userId,
      resolvedAt: null,
      cancelledAt: null,
    },
    orderBy: { cooldownStartedAt: "desc" },
  });
}

export async function createCooldown(
  userId: string,
  jti: string,
  cooldownEndsAt: Date,
  reason?: string,
) {
  const db = usePrisma();
  return db.cooldownRequest.create({
    data: {
      userId,
      reason: reason ?? null,
      cooldownEndsAt,
      tokenJti: jti,
    },
  });
}

export async function resolveCooldown(id: string) {
  const db = usePrisma();
  return db.cooldownRequest.update({
    where: { id },
    data: { resolvedAt: new Date() },
  });
}

export async function cancelCooldown(id: string) {
  const db = usePrisma();
  return db.cooldownRequest.update({
    where: { id },
    data: { cancelledAt: new Date() },
  });
}
