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 GET(req: Request) {
    try {
        const { userId } = await auth()
        if (!userId) return new NextResponse('Unauthorized', { status: 401 })

        const db = await getDatabase()

        // Ensure user is synced (handles seed script ID mismatch)
        // We need to import ensureUserSynced
        const user = await ensureUserSynced(userId, db)

        if (!user || (user.role !== 'admin' && user.role !== 'superAdmin')) {
            return new NextResponse('Forbidden', { status: 403 })
        }

        const attendance = await db.getAllAttendance()
        return NextResponse.json(attendance)
    } catch (error) {
        console.error('Admin attendance error:', error)
        return new NextResponse('Internal Server Error', { status: 500 })
    }
}
