import { createClient } from '@/lib/supabase/server'
import { redirect, notFound } from 'next/navigation'
import { JoinRound } from '@/components/round/join-round'

export default async function JoinRoundPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params
  const supabase = await createClient()
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const db = supabase as any

  const {
    data: { user },
  } = await supabase.auth.getUser()
  if (!user) redirect(`/login`)

  const { data: round } = await db
    .from('rounds')
    .select(
      `
      id, name, date, holes_count, status, created_by,
      course:courses (name),
      tee:tees (name, color),
      round_players (user_id)
    `,
    )
    .eq('id', id)
    .single()

  if (!round) notFound()

  // Already a member — go straight to the round
  const alreadyJoined = round.round_players?.some(
    (p: { user_id: string }) => p.user_id === user.id,
  )
  if (alreadyJoined) redirect(`/rounds/${id}`)

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

  return <JoinRound round={round} userId={user.id} />
}
