import type { PrismaClient, CompetitionCategory, EvaluationForm } from '@prisma/client'

/**
 * Find the active EvaluationForm for a round, with category-aware resolution.
 *
 * Resolution order:
 * 1. If `category` is provided, try the category-specific active form first.
 * 2. Fall back to the shared form (category = null).
 * 3. If no `category` provided, return the shared form directly.
 */
export async function findActiveForm(
  prisma: PrismaClient | Pick<PrismaClient, 'evaluationForm'>,
  roundId: string,
  category?: CompetitionCategory | null,
): Promise<EvaluationForm | null> {
  if (category) {
    const specific = await prisma.evaluationForm.findFirst({
      where: { roundId, isActive: true, category },
    })
    if (specific) return specific
  }
  // Fallback to shared form (category = null)
  return prisma.evaluationForm.findFirst({
    where: { roundId, isActive: true, category: null },
  })
}
