import { NextRequest, NextResponse } from "next/server";
import { restApiFetch } from "@/utils/bagisto";
import { isBagistoError } from "@/utils/type-guards";
import { getAuthToken } from "@/utils/helper";

export async function GET(req: NextRequest) {
  try {
    const guestToken = getAuthToken(req);

    // 👇 取出所有前端传过来的查询参数
    const searchParams = req.nextUrl.searchParams;
    const page = searchParams.get("page");
    const per_page = searchParams.get("per_page");
    const amountType = searchParams.get("amountType");

    // 👇 构建查询参数数组（自动过滤空值）
    const queryParts: string[] = [];
    if (page) queryParts.push(`page=${page}`);
    if (per_page) queryParts.push(`per_page=${per_page}`);
    if (amountType) queryParts.push(`amountType=${amountType}`);

    // 👇 最终拼接 URL
    let apiUrl = "/customer/reward-points/history";
    if (queryParts.length > 0) {
      apiUrl += "?" + queryParts.join("&");
    }

    console.log("最终请求API地址：", apiUrl);

    const response = await restApiFetch<any>({
      api: apiUrl,
      method: "GET",
      cache: "no-store",
      guestToken,
    });

    return NextResponse.json({
      status: response.status,
      data: response.body,
    });

  } catch (error) {
    if (isBagistoError(error)) {
      return NextResponse.json(
        {
          data: null,
          error: error.cause ?? error,
        },
        { status: 200 }
      );
    }

    return NextResponse.json(
      {
        message: "Network error",
        error: error instanceof Error ? error.message : error,
      },
      { status: 500 }
    );
  }
}