import { NextRequest, NextResponse } from "next/server";

const COMMUNITY_URL = process.env.COMMUNITY_URL || process.env.UMMAHID_URL || "http://ummahid:3000";

export async function POST(request: NextRequest) {
  const authHeader = request.headers.get("authorization");
  if (!authHeader) {
    return NextResponse.json({ error: "Authorization required" }, { status: 401 });
  }

  try {
    const body = await request.json();
    const { amount } = body;

    // If amount is 0 or not provided, return status summary (remaining obligation, nisab, etc.)
    if (!amount || typeof amount !== "number" || amount < 0) {
      return NextResponse.json(
        { error: "Amount is required and must be non-negative" },
        { status: 400 }
      );
    }

    if (amount === 0) {
      // Return zakat status summary
      const ummahRes = await fetch(`${COMMUNITY_URL}/api/v2/zakat/status`, {
        method: "GET",
        headers: {
          Authorization: authHeader,
        },
      });
      const data = await ummahRes.json();
      return NextResponse.json(data, { status: ummahRes.status });
    }

    const ummahRes = await fetch(`${COMMUNITY_URL}/api/v2/zakat/calculate`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: authHeader,
      },
      body: JSON.stringify({ amount }),
    });

    const data = await ummahRes.json();
    return NextResponse.json(data, { status: ummahRes.status });
  } catch (error) {
    console.error("[zakat-calculate] Proxy error:", error);
    return NextResponse.json(
      { error: "Failed to calculate zakat" },
      { status: 502 }
    );
  }
}
