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

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

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

  try {
    const ummahRes = await fetch(`${UMMAHID_URL}/api/flh/wallet/ton-address`, {
      headers: { Authorization: authHeader },
    });
    const data = await ummahRes.json();
    return NextResponse.json(data, { status: ummahRes.status });
  } catch (error) {
    console.error("[ton-address] Proxy error:", error);
    return NextResponse.json({ error: "Failed to fetch TON address" }, { status: 502 });
  }
}

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

  try {
    const body = await req.json();
    const ummahRes = await fetch(`${UMMAHID_URL}/api/flh/wallet/ton-address`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: authHeader,
      },
      body: JSON.stringify(body),
    });
    const data = await ummahRes.json();
    return NextResponse.json(data, { status: ummahRes.status });
  } catch (error) {
    console.error("[ton-address] Proxy error:", error);
    return NextResponse.json({ error: "Failed to save TON address" }, { status: 502 });
  }
}
