import { auth } from '@/lib/auth'
import { db } from '@/lib/db'
import { courses, tees } from '@/lib/db/schema'
import { eq } from 'drizzle-orm'
import { headers } from 'next/headers'
import { redirect } from 'next/navigation'
import { NewRoundWizard } from '@/components/round/new-round-wizard'

export default async function NewRoundPage() {
  const session = await auth.api.getSession({ headers: await headers() })
  if (!session) redirect('/login')

  const courseList = await db.select().from(courses).orderBy(courses.name)

  const teesData = await db.select().from(tees)
  const teesById = teesData.reduce<Record<string, typeof teesData>>((acc, tee) => {
    ;(acc[tee.courseId] ??= []).push(tee)
    return acc
  }, {})

  const coursesWithTees = courseList.map((c) => ({
    id:   c.id,
    name: c.name,
    par:  c.par,
    tees: (teesById[c.id] ?? []).map((t) => ({
      id:            t.id,
      name:          t.name,
      color:         t.color,
      course_rating: parseFloat(t.courseRating),
      slope_rating:  t.slopeRating,
    })),
  }))

  return <NewRoundWizard courses={coursesWithTees} />
}
