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

export default async function RoundPage({ 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, status, holes_count, created_by,
      course:courses (id, name, par),
      tee:tees (id, name, color, course_rating, slope_rating)
    `,
    )
    .eq('id', id)
    .single()

  if (!round) notFound()

  const { data: players } = await db
    .from('round_players')
    .select(
      `
      id, role, handicap_index, course_handicap, joined_at,
      profile:profiles (id, display_name, avatar_url)
    `,
    )
    .eq('round_id', id)
    .order('joined_at')

  const { data: invites } = await db
    .from('round_invites')
    .select('id, email, accepted_at, created_at')
    .eq('round_id', id)
    .is('accepted_at', null)
    .order('created_at')

  const isCreator = round.created_by === user.id

  if (round.status === 'active' || round.status === 'completed') {
    redirect(`/rounds/${id}/scorecard`)
  }

  return (
    <RoundLobby
      round={round}
      players={players ?? []}
      pendingInvites={invites ?? []}
      currentUserId={user.id}
      isCreator={isCreator}
    />
  )
}
