import { auth } from "@clerk/nextjs/server";
import { NextResponse } from "next/server";
import { getDatabase } from "@/lib/database";
import log from "@/lib/logger";

export async function POST(req: Request) {
  try {
    const { userId } = await auth();
    if (!userId) return new NextResponse("Unauthorized", { status: 401 });

    const db = await getDatabase();

    const activeCheckIn = await db.getActiveCheckIn(userId);
    if (!activeCheckIn) {
      return new NextResponse("No active check-in found", { status: 404 });
    }

    const attendance = await db.checkOut(activeCheckIn.id);
    return NextResponse.json(attendance);
  } catch (error) {
    log.error("Failed to check out", error);
    return new NextResponse("Internal Server Error", { status: 500 });
  }
}
