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

export default async function RoundPage({ 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,
      status:     rounds.status,
      holesCount: rounds.holesCount,
      createdBy:  rounds.createdBy,
      courseName: courses.name,
      teeName:    tees.name,
      teeColor:   tees.color,
      courseRating: tees.courseRating,
      slopeRating:  tees.slopeRating,
    })
    .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()
  if (round.status === 'active' || round.status === 'completed') {
    redirect(`/rounds/${id}/scorecard`)
  }

  const players = await db
    .select({
      id:             roundPlayers.id,
      userId:         roundPlayers.userId,
      role:           roundPlayers.role,
      handicapIndex:  roundPlayers.handicapIndex,
      courseHandicap: roundPlayers.courseHandicap,
      joinedAt:       roundPlayers.joinedAt,
      displayName:    user.name,
      avatarUrl:      user.image,
    })
    .from(roundPlayers)
    .innerJoin(user, eq(roundPlayers.userId, user.id))
    .where(eq(roundPlayers.roundId, id))
    .orderBy(roundPlayers.joinedAt)

  const pendingInvites = await db
    .select({ id: roundInvites.id, email: roundInvites.email, createdAt: roundInvites.createdAt })
    .from(roundInvites)
    .where(eq(roundInvites.roundId, id))

  return (
    <RoundLobby
      round={{
        id:         round.id,
        name:       round.name,
        date:       round.date,
        status:     round.status,
        holesCount: round.holesCount,
        createdBy:  round.createdBy,
        course:     { name: round.courseName },
        tee:        { name: round.teeName, color: round.teeColor },
      }}
      players={players.map((p) => ({
        id:             p.id,
        role:           p.role,
        handicapIndex:  p.handicapIndex,
        courseHandicap: p.courseHandicap,
        profile: { id: p.userId, displayName: p.displayName, avatarUrl: p.avatarUrl },
      }))}
      pendingInvites={pendingInvites.map((i) => ({ id: i.id, email: i.email, createdAt: i.createdAt, acceptedAt: null }))}
      currentUserId={session.user.id}
      isCreator={round.createdBy === session.user.id}
    />
  )
}
