import type { Metadata } from 'next'
import { prisma } from '@/lib/prisma'
import { SemiFinalistsContent } from '@/components/admin/semi-finalists-content'

export const metadata: Metadata = { title: 'Semi-Finalists' }
export const dynamic = 'force-dynamic'

type PageProps = {
  searchParams: Promise<{ editionId?: string }>
}

export default async function SemiFinalistsPage({ searchParams }: PageProps) {
  const params = await searchParams
  let editionId = params.editionId || null

  if (!editionId) {
    const defaultEdition = await prisma.program.findFirst({
      where: { status: 'ACTIVE' },
      orderBy: { year: 'desc' },
      select: { id: true },
    })
    editionId = defaultEdition?.id || null

    if (!editionId) {
      const anyEdition = await prisma.program.findFirst({
        orderBy: { year: 'desc' },
        select: { id: true },
      })
      editionId = anyEdition?.id || null
    }
  }

  if (!editionId) {
    return (
      <div className="py-12 text-center text-muted-foreground">
        No edition found.
      </div>
    )
  }

  return <SemiFinalistsContent editionId={editionId} />
}
