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

// Confirmed live: POST /user/wallet/transaction/details takes
// {id, transactionType} (both required — a real backend 400s
// "id and transactionType are required" without them) and returns a
// single {status, message, data} object, not a list — a different
// endpoint from /user/wallet/transactions (the list one), despite both
// living under /wallet. `transactionType` must be the exact value the
// list endpoint returned for that row (CHAT/CALL/ORDER/RECHARGE/etc)
// since the backend uses it to pick which table to search
// (user_chat_histories / user_call_histories / user_orders /
// wallettransaction) — a row only comes back if it belongs to the
// user in the token, otherwise a real 404 "Transaction not found".
const API_BASE = "https://api.astrology.togwe.com/api/user/wallet/transaction/details";

export async function POST(request: NextRequest) {
  try {
    const authorization = request.headers.get("authorization");

    if (!authorization) {
      return NextResponse.json(
        { status: 401, message: "Authentication token is required." },
        { status: 401 },
      );
    }

    const body = await request.json().catch(() => ({}));

    const response = await fetch(API_BASE, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
        Authorization: authorization,
      },
      body: JSON.stringify(body),
      cache: "no-store",
    });

    const data = await response.json();

    return NextResponse.json(data, { status: response.status });
  } catch (error) {
    console.error("Wallet transaction details proxy error:", error);

    return NextResponse.json(
      { status: 500, message: "Unable to connect to the wallet API." },
      { status: 500 },
    );
  }
}
