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

export async function GET() {
  const rows = await db
    .select({ id: annotators.id, displayName: annotators.displayName })
    .from(annotators);

  return NextResponse.json(rows);
}

export async function POST(request: Request) {
  const body = await request.json();
  const { annotatorId, password } = body as {
    annotatorId?: string;
    password?: string;
  };

  if (!annotatorId || !password) {
    return NextResponse.json(
      { error: "Invalid credentials" },
      { status: 401 },
    );
  }

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

  if (!annotator || annotator.password.toLowerCase() !== password.toLowerCase()) {
    return NextResponse.json(
      { error: "Invalid credentials" },
      { status: 401 },
    );
  }

  await createSession(annotatorId);

  return NextResponse.json({
    ok: true,
    annotator: { id: annotator.id, displayName: annotator.displayName },
  });
}

export async function DELETE() {
  await destroySession();
  return NextResponse.json({ ok: true });
}
