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

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

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

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

  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,
      EXTENSION_KIND.API_RATE_LIMIT,
    );
    return NextResponse.json(result);
  } catch (err) {
    const msg = err instanceof Error ? err.message : "Failed to submit request";
    return NextResponse.json({ error: msg }, { status: 400 });
  }
}
