63 lines
2.0 KiB
TypeScript
63 lines
2.0 KiB
TypeScript
'use server'
|
|
|
|
import { z } from 'zod'
|
|
import { createClient } from '@/lib/supabase/server'
|
|
import { revalidatePath } from 'next/cache'
|
|
|
|
const TeeInput = z.object({
|
|
name: z.string().min(1, 'Tee name required'),
|
|
color: z.string().regex(/^#[0-9a-fA-F]{6}$/),
|
|
course_rating: z.coerce.number().min(50).max(80),
|
|
slope_rating: z.coerce.number().int().min(55).max(155),
|
|
})
|
|
|
|
const HoleInput = z.object({
|
|
hole_number: z.number().int().min(1).max(18),
|
|
par: z.number().int().min(3).max(5),
|
|
stroke_index: z.number().int().min(1).max(18),
|
|
})
|
|
|
|
export const CreateCourseSchema = z.object({
|
|
name: z.string().min(1, 'Course name required').max(100),
|
|
par: z.number().int().min(27).max(90),
|
|
tees: z.array(TeeInput).min(1, 'At least one tee required'),
|
|
holes: z.array(HoleInput).min(9),
|
|
})
|
|
|
|
export type CreateCourseInput = z.infer<typeof CreateCourseSchema>
|
|
|
|
export async function createCourse(data: CreateCourseInput) {
|
|
const parsed = CreateCourseSchema.safeParse(data)
|
|
if (!parsed.success) {
|
|
return { error: parsed.error.issues[0]?.message ?? 'Invalid data' }
|
|
}
|
|
|
|
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) return { error: 'Not authenticated' }
|
|
|
|
const { data: course, error: courseError } = await db
|
|
.from('courses')
|
|
.insert({ name: parsed.data.name, par: parsed.data.par, created_by: user.id })
|
|
.select('id')
|
|
.single()
|
|
if (courseError) return { error: courseError.message }
|
|
|
|
const { error: teesError } = await db
|
|
.from('tees')
|
|
.insert(parsed.data.tees.map((t) => ({ ...t, course_id: course.id })))
|
|
if (teesError) return { error: teesError.message }
|
|
|
|
const { error: holesError } = await db
|
|
.from('holes')
|
|
.insert(parsed.data.holes.map((h) => ({ ...h, course_id: course.id })))
|
|
if (holesError) return { error: holesError.message }
|
|
|
|
revalidatePath('/rounds/new')
|
|
return { courseId: course.id as string }
|
|
}
|