import { auth } from '@/lib/auth'
import { db } from '@/lib/db'
import { rounds, roundPlayers, courses, tees } from '@/lib/db/schema'
import { eq } from 'drizzle-orm'
import { redirect, notFound } from 'next/navigation'
import { headers } from 'next/headers'
import { JoinRound } from '@/components/round/join-round'

export default async function JoinRoundPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params
  const session = await auth.api.getSession({ headers: await headers() })
  if (!session) redirect(`/login`)

  const [round] = await db
    .select({
      id:         rounds.id,
      name:       rounds.name,
      date:       rounds.date,
      holesCount: rounds.holesCount,
      status:     rounds.status,
      courseName: courses.name,
      teeName:    tees.name,
      teeColor:   tees.color,
    })
    .from(rounds)
    .innerJoin(courses, eq(rounds.courseId, courses.id))
    .innerJoin(tees, eq(rounds.teeId, tees.id))
    .where(eq(rounds.id, id))
    .limit(1)

  if (!round) notFound()

  // Already a member — go straight to the round
  const [membership] = await db
    .select({ id: roundPlayers.id })
    .from(roundPlayers)
    .where(eq(roundPlayers.roundId, id))
    .limit(1)

  if (membership) redirect(`/rounds/${id}`)

  // Round must be in lobby to join
  if (round.status !== 'lobby') redirect('/dashboard')

  return (
    <JoinRound
      roundId={id}
      round={{
        name:       round.name,
        date:       round.date,
        holesCount: round.holesCount,
        course:     { name: round.courseName },
        tee:        { name: round.teeName, color: round.teeColor },
      }}
    />
  )
}
