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

export async function GET(req: Request) {
  log.apiRequest("GET", "/api/attendance/history", {
    headers: Object.fromEntries(req.headers.entries()),
  });

  try {
    const authResult = await auth();
    const { userId } = authResult;
    log.debug("Auth result received", { authResult });

    if (!userId) {
      log.warn("No userId found in auth result");
      return new NextResponse("Unauthorized", { status: 401 });
    }

    const db = await getDatabase();

    // Ensure user exists in DB (sync from Clerk if needed)
    await ensureUserSynced(userId, db);

    const history = await db.getAttendanceHistory(userId);
    return NextResponse.json(history);
  } catch (error) {
    log.error("Failed to fetch attendance history", error);
    return new NextResponse("Internal Server Error", { status: 500 });
  }
}
