import { createServerFn } from '@tanstack/react-start'
import { z } from 'zod'
import {
  createReservationRecord,
  fetchBrews,
  fetchExperiences,
  fetchMenuCategories,
  fetchMenuItems,
  fetchPairings,
  fetchSettings,
  fetchStats,
  fetchTestimonials,
} from './pb'

export const getSettings = createServerFn({ method: 'GET' }).handler(() => fetchSettings())

export const getHomeData = createServerFn({ method: 'GET' }).handler(async () => {
  const [stats, brews, experiences, testimonials] = await Promise.all([
    fetchStats(),
    fetchBrews(),
    fetchExperiences(),
    fetchTestimonials(),
  ])
  return {
    stats,
    featuredBrews: brews.filter((b) => b.featured).slice(0, 4),
    experiences,
    testimonials,
  }
})

export const getBrewsData = createServerFn({ method: 'GET' }).handler(async () => {
  const brews = await fetchBrews()
  return {
    flagship: brews.find((b) => b.flagship) ?? null,
    coreBrews: brews.filter((b) => b.on_tap),
    seasonalBrews: brews.filter((b) => b.seasonal),
    flightBrews: brews.filter((b) => b.flight),
  }
})

export const getMenuData = createServerFn({ method: 'GET' }).handler(async () => {
  const [categories, items, pairings] = await Promise.all([
    fetchMenuCategories(),
    fetchMenuItems(),
    fetchPairings(),
  ])
  return { categories, items, pairings }
})

export const getVisitData = createServerFn({ method: 'GET' }).handler(() => fetchSettings())

const reservationSchema = z.object({
  name: z.string().trim().min(2, 'Please tell us your name'),
  phone: z.string().trim().min(7, 'Please provide a valid phone number'),
  source: z.enum(['table', 'quick', 'flight']),
  date: z.string().optional(),
  time: z.string().optional(),
  guests: z.string().optional(),
  requests: z.string().optional(),
})

export const createReservation = createServerFn({ method: 'POST' })
  .validator(reservationSchema)
  .handler(async ({ data }) => {
    await createReservationRecord(data)
    return { ok: true as const }
  })
