import { NextResponse } from "next/server";
import { db } from "@/db";
import { annotators } from "@/db/schema";
import { eq } from "drizzle-orm";
import { getSession } from "@/lib/auth";

export async function GET() {
  const session = await getSession();
  if (!session) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const [annotator] = await db
    .select({ onboardedAt: annotators.onboardedAt })
    .from(annotators)
    .where(eq(annotators.id, session.annotatorId))
    .limit(1);

  return NextResponse.json({
    onboarded: !!annotator?.onboardedAt,
  });
}

export async function POST(request: Request) {
  const session = await getSession();
  if (!session) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const body = await request.json();
  const { action } = body as { action?: string };

  if (action === "complete") {
    await db
      .update(annotators)
      .set({ onboardedAt: new Date() })
      .where(eq(annotators.id, session.annotatorId));

    return NextResponse.json({ ok: true });
  }

  return NextResponse.json({ error: "Invalid action" }, { status: 400 });
}
