import { NextRequest, NextResponse } from "next/server"; const BE_BASE_URL = process.env.BE_BASE_URL || "http://localhost:5000"; const COOKIE_NAME = "auth_token"; export async function POST(request: NextRequest) { try { const { cookies } = await import("next/headers"); const cookieStore = await cookies(); const token = cookieStore.get(COOKIE_NAME)?.value; if (!token) { return NextResponse.json( { message: "Missing Authorization header" }, { status: 401 } ); } // Parse request body const body = await request.json(); const { filters = {}, pagination = { page: 1, limit: 10 }, sort } = body; // Build query string for backend const queryParts: string[] = []; // Add pagination (standard key=value format) queryParts.push(`limit=${pagination.limit}`); queryParts.push(`page=${pagination.page}`); // Add sorting if provided (still key=value) if (sort) { queryParts.push(`sort=${sort.field}:${sort.order}`); } // Process filters - convert FilterValue objects to operator/value format for (const [key, filterValue] of Object.entries(filters)) { if (!filterValue) continue; let op: string; let value: string; if (typeof filterValue === "string") { // Simple string filter - default to == op = "=="; value = filterValue; } else { // FilterValue object with operator and value const filterVal = filterValue as { operator?: string; value: string }; op = filterVal.operator || "=="; value = filterVal.value; } if (!value) continue; // Encode value to prevent breaking URL const encodedValue = encodeURIComponent(value); queryParts.push(`${key}=${op}/${encodedValue}`); } const queryString = queryParts.join("&"); const backendUrl = `${BE_BASE_URL}/api/v1/transactions${queryString ? `?${queryString}` : ""}`; console.log("[DEBUG] [TRANSACTIONS] Backend URL:", backendUrl); const response = await fetch(backendUrl, { method: "GET", headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, cache: "no-store", }); if (!response.ok) { const errorData = await response .json() .catch(() => ({ message: "Failed to fetch transactions" })); return NextResponse.json( { success: false, message: errorData?.message || "Failed to fetch transactions", }, { status: response.status } ); } const data = await response.json(); console.log("[DEBUG] [TRANSACTIONS] Response data:", data); return NextResponse.json(data, { status: response.status }); } catch (err: unknown) { console.error("Proxy GET /api/v1/transactions error:", err); const errorMessage = err instanceof Error ? err.message : "Unknown error"; return NextResponse.json( { message: "Internal server error", error: errorMessage }, { status: 500 } ); } }