import { NextRequest, NextResponse } from "next/server";
import dbConnect from "@/lib/connectdb";
import Transaction from "@/models/transactions";
import { User } from "@/models/user"; // Import User model
import { getServerSession } from "next-auth";
import { authOptions } from "@/auth";

export async function GET(req: NextRequest) {
  await dbConnect();

  try {
    const session = await getServerSession(authOptions);
    if (!session) {
      return NextResponse.json({ message: "Unauthorized" }, { status: 401 });
    }

    // Check if user is admin
    const userRole = session.user.role;
    if (userRole !== "admin") {
      return NextResponse.json(
        { message: "Admin access required" },
        { status: 403 }
      );
    }

    // Get search query from URL parameters
    const { searchParams } = new URL(req.url);
    const searchQuery = searchParams.get("search");

    let transactions;
    let userWalletBalance = null;

    if (searchQuery) {
      // Search for user by email, name, or userId
      const user = await User.findOne({
        $or: [
          { email: { $regex: searchQuery, $options: "i" } },
          { name: { $regex: searchQuery, $options: "i" } },
          { userId: searchQuery }, // Assuming userId is a string that might match exactly
        ],
      });

      if (user) {
        // Get user's wallet balance
        userWalletBalance = user.accountBalance;

        // Get transactions for this user
        transactions = await Transaction.find({ userId: user._id });
      } else {
        // If no user found, return empty transactions
        transactions = [];
      }
    } else {
      // If no search query, get all transactions
      transactions = await Transaction.find({});
    }

    // Return transactions and user wallet balance if available
    return NextResponse.json(
      {
        transactions,
        ...(userWalletBalance !== null && { userWalletBalance }),
      },
      { status: 200 }
    );
  } catch (error) {
    console.error("Error fetching transactions:", error);
    return NextResponse.json(
      { message: "Error fetching transactions", error },
      { status: 500 }
    );
  }
}
