import { auth } from '@clerk/nextjs/server' import { NextResponse } from 'next/server' import { getDatabase } from '@/lib/database' import { ensureUserSynced } from '@/lib/sync-user' export async function POST(req: Request) { try { const { userId } = await auth() if (!userId) return new NextResponse('Unauthorized', { status: 401 }) const db = await getDatabase() // Ensure user exists in DB (sync from Clerk if needed) await ensureUserSynced(userId, db) let client = await db.getClientByUserId(userId) if (!client) { // Auto-create client profile if it doesn't exist console.log('Client profile not found, creating new one for user:', userId) client = await db.createClient({ userId, membershipType: 'basic', membershipStatus: 'active', joinDate: new Date() }) } // Check if already checked in const activeCheckIn = await db.getActiveCheckIn(client.id) if (activeCheckIn) { return new NextResponse('Already checked in', { status: 400 }) } const body = await req.json() const { type = 'gym', notes } = body const attendance = await db.checkIn(client.id, type, notes) return NextResponse.json(attendance) } catch (error) { console.error('Check-in error:', error) return new NextResponse('Internal Server Error', { status: 500 }) } }