import { NextRequest, NextResponse } from "next/server";
import {
  approveQuotaExtensionRequest,
  rejectQuotaExtensionRequest,
} from "@/lib/quota-extensions";

function isAuthorized(req: NextRequest) {
  const key = process.env.ADMIN_API_KEY;
  if (!key) return false;
  const auth = req.headers.get("authorization");
  return auth === `Bearer ${key}`;
}

export async function POST(
  req: NextRequest,
  { params }: { params: Promise<{ id: string }> },
) {
  if (!isAuthorized(req)) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const { id } = await params;
  let action: "approve" | "reject" = "approve";
  let bonusQuota: number | undefined;
  let bonusRateLimit: number | undefined;
  let adminNote: string | undefined;

  try {
    const body = await req.json();
    if (body.action === "reject") action = "reject";
    if (typeof body.bonusQuota === "number" && Number.isFinite(body.bonusQuota)) {
      bonusQuota = body.bonusQuota;
    }
    if (typeof body.bonusRateLimit === "number" && Number.isFinite(body.bonusRateLimit)) {
      bonusRateLimit = body.bonusRateLimit;
    }
    if (typeof body.adminNote === "string") adminNote = body.adminNote;
  } catch {
    // defaults
  }

  try {
    if (action === "reject") {
      await rejectQuotaExtensionRequest(id, adminNote);
    } else {
      await approveQuotaExtensionRequest(id, { bonusQuota, bonusRateLimit, adminNote });
    }
    return NextResponse.json({ ok: true });
  } catch (err) {
    const msg = err instanceof Error ? err.message : "Failed to process request";
    return NextResponse.json({ error: msg }, { status: 400 });
  }
}
