import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { db } from "@/lib/db";

/**
 * POST /api/auth/device-code/approve
 *
 * Called from the /activate page when a logged-in user submits the user_code.
 * Links the device code to the user, marking it as approved.
 */
export async function POST(req: NextRequest) {
  const session = await auth();

  if (!session?.user?.id) {
    return NextResponse.json({ error: "Unauthorized. Please sign in first." }, { status: 401 });
  }

  try {
    const body = await req.json();
    const { user_code } = body;

    if (!user_code || typeof user_code !== "string") {
      return NextResponse.json(
        { error: "user_code is required" },
        { status: 400 },
      );
    }

    // Normalize: uppercase, trim
    const normalizedCode = user_code.trim().toUpperCase();

    const record = await db.deviceCode.findUnique({
      where: { userCode: normalizedCode },
    });

    if (!record) {
      return NextResponse.json(
        { error: "Invalid code. Please check and try again." },
        { status: 404 },
      );
    }

    // Check expiry
    if (new Date() > record.expires) {
      await db.deviceCode.delete({ where: { id: record.id } });
      return NextResponse.json(
        { error: "Code expired. Please run `llmhosts up` again to get a new code." },
        { status: 410 },
      );
    }

    // Already approved
    if (record.approved) {
      return NextResponse.json(
        { error: "This code has already been used." },
        { status: 409 },
      );
    }

    // Approve: link to the authenticated user
    await db.deviceCode.update({
      where: { id: record.id },
      data: {
        userId: session.user.id,
        approved: true,
      },
    });

    return NextResponse.json({
      message: "Device authorized! You can close this page. Your CLI is now connected.",
    });
  } catch {
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 },
    );
  }
}
