import { NextResponse } from "next/server";
import { randomBytes } from "crypto";
import { db } from "@/lib/db";

/**
 * POST /api/auth/device-code
 *
 * RFC 8628 Device Authorization Grant — Step 1.
 * CLI calls this to get a device_code + user_code.
 * User enters user_code at /activate to approve.
 */
export async function POST() {
  try {
    // Generate codes
    const deviceCode = randomBytes(32).toString("hex");
    const userCode = generateUserCode(); // Human-readable: ABCD-1234

    // Expires in 15 minutes
    const expires = new Date(Date.now() + 15 * 60 * 1000);

    await db.deviceCode.create({
      data: {
        deviceCode,
        userCode,
        expires,
      },
    });

    return NextResponse.json({
      device_code: deviceCode,
      user_code: userCode,
      verification_uri: `${process.env.NEXTAUTH_URL || "https://llmhosts.com"}/activate`,
      expires_in: 900, // 15 minutes
      interval: 5, // poll every 5 seconds
    });
  } catch {
    return NextResponse.json(
      { error: "Failed to generate device code" },
      { status: 500 },
    );
  }
}

/**
 * Generate a human-readable code like "ABCD-1234".
 * 4 uppercase letters + hyphen + 4 digits = ~2.8 billion combinations.
 */
function generateUserCode(): string {
  const letters = "ABCDEFGHJKLMNPQRSTUVWXYZ"; // no I, O (confusable)
  const digits = "0123456789";

  let code = "";
  const bytes = randomBytes(8);
  for (let i = 0; i < 4; i++) {
    code += letters[bytes[i] % letters.length];
  }
  code += "-";
  for (let i = 4; i < 8; i++) {
    code += digits[bytes[i] % digits.length];
  }
  return code;
}
