// pages/api/wallet/transactions.ts
import { NextRequest, NextResponse } from "next/server";
import Transaction from "@/models/transactions";
import { authOptions } from "@/auth";
import { getServerSession } from "next-auth";

export async function GET(req: NextRequest) {
  try {
    const session = await getServerSession(authOptions);
    if (!session || session.user.role !== "admin") {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }
    const { searchParams } = new URL(req.url);
    const userId = searchParams.get("userId");
    const type = searchParams.get("type");

    if (!userId) {
      return NextResponse.json(
        { message: "User ID is required" },
        { status: 400 }
      );
    }

    let query: any = { userId };

    if (type) {
      query.type = { $in: type.split(",") };
    }

    const transactions = await Transaction.find(query)
      .sort({ createdAt: -1 })
      .limit(10);

    return NextResponse.json({ transactions });
  } catch (error) {
    console.error("Get transactions error:", error);
    return NextResponse.json(
      { message: "Failed to fetch transactions" },
      { status: 500 }
    );
  }
}
