import { NextRequest, NextResponse } from "next/server";
import { createQuotaExtensionRequest, getQuotaExtensionUsage } from "@/lib/quota-extensions";
import { getSessionUser } from "@/lib/session";

export async function GET() {
  const user = await getSessionUser();
  if (!user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const usage = await getQuotaExtensionUsage(user.id);
  return NextResponse.json(usage);
}

export async function POST(req: NextRequest) {
  const user = await getSessionUser();
  if (!user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  let message = "";
  try {
    const body = await req.json();
    if (typeof body.message === "string") message = body.message;
  } catch {
    // optional body
  }

  try {
    const result = await createQuotaExtensionRequest(user.id, message);
    return NextResponse.json(result);
  } catch (err) {
    const msg = err instanceof Error ? err.message : "Failed to submit request";
    return NextResponse.json({ error: msg }, { status: 400 });
  }
}
