import { createServerFn, createServerOnlyFn } from '@tanstack/react-start' import { eq } from 'drizzle-orm' import { z } from 'zod' import { db } from '#/db' import { restaurantSettings } from '#/db/schema' import { requireStaffSession } from '#/lib/auth' import { zodValidator } from '#/lib/server-validator' import { dataUrlImageSchema } from '#/lib/table-image' // Reads never require a session — the public booking form needs the interval and // lead time to generate its own time-slot grid, just like getTables(). Exported // (rather than only reachable through the server fn below) so reservations.ts can // read the current settings directly while validating a booking. This module is // imported by client-reachable route files for the createServerFns below, so — // same issue as `#/lib/auth` — a plain, unwrapped export using `db` directly would // drag the Postgres driver into the browser bundle; `createServerOnlyFn` keeps it // server-side only. export const loadReservationSettings = createServerOnlyFn(async function loadReservationSettings() { const [existing] = await db.select().from(restaurantSettings).limit(1) if (existing) return existing const [created] = await db.insert(restaurantSettings).values({}).returning() return created }) export const getReservationSettings = createServerFn({ method: 'GET' }).handler(async () => { return loadReservationSettings() }) const updateReservationSettingsSchema = z.object({ reservationIntervalMinutes: z.number().int().min(5).max(120), reservationDurationMinutes: z.number().int().min(15).max(480), minLeadTimeMinutes: z.number().int().min(0).max(10080), maxLeadTimeDays: z.number().int().min(1).max(365), tableDisplayMode: z.enum(['individual', 'overview']), tableOverviewImageUrl: dataUrlImageSchema, }) export const updateReservationSettings = createServerFn({ method: 'POST' }) .validator(zodValidator(updateReservationSettingsSchema)) .handler(async ({ data }) => { console.log('[settings] updateReservationSettings called with', data) const session = await requireStaffSession() console.log('[settings] session role:', session.user.role) if (session.user.role !== 'admin') { throw new Error('Nur Admins dürfen die Einstellungen ändern') } const existing = await loadReservationSettings() console.log('[settings] existing row before update:', existing) const [updated] = await db .update(restaurantSettings) .set(data) .where(eq(restaurantSettings.id, existing.id)) .returning() console.log('[settings] row after update:', updated) return updated })