import { NextResponse } from "next/server";
import { createUserApiKey, getUserApiKeyStatus, revokeUserApiKey } from "@/lib/api-keys";
import { hasProFeatures } from "@/lib/edition";
import { getSessionUser } from "@/lib/session";

async function requireApiKeyAccess() {
  const user = await getSessionUser();
  if (!user) {
    return { error: NextResponse.json({ error: "Unauthorized" }, { status: 401 }), user: null };
  }
  if (!hasProFeatures(user.plan)) {
    return {
      error: NextResponse.json(
        { error: "API keys are available on the Pro plan only" },
        { status: 403 },
      ),
      user: null,
    };
  }
  return { error: null, user };
}

export async function GET() {
  const { error, user } = await requireApiKeyAccess();
  if (error || !user) return error!;

  const status = await getUserApiKeyStatus(user.id);
  return NextResponse.json(status);
}

export async function POST() {
  const { error, user } = await requireApiKeyAccess();
  if (error || !user) return error!;

  const { token, prefix } = await createUserApiKey(user.id);
  return NextResponse.json({
    apiKey: token,
    prefix,
    message: "Copy this key now. It will not be shown again.",
  });
}

export async function DELETE() {
  const { error, user } = await requireApiKeyAccess();
  if (error || !user) return error!;

  await revokeUserApiKey(user.id);
  return NextResponse.json({ ok: true });
}
