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

export const dynamic = "force-dynamic";

export async function GET(req: NextRequest) {
  try {
    // Connect to MongoDB
    await dbConnect();
    const session = await getServerSession(authOptions);

    if (!session) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const userId = session?.user?.id; // Get user ID from the token

    // Fetch user account balance and referral bonus
    const user = await User.findById(userId).select(
      "accountBalance refererBonus"
    );
    console.log(user);

    if (!user) {
      return NextResponse.json(
        { error: "If the user exists, they will be handled accordingly." },
        { status: 404 }
      );
    }

    // Fetch all transactions for the user
    const transactions = await Transaction.find({ userId });

    // Calculate Total Funding
    const totalFunding = transactions
      .filter(
        (transaction) =>
          transaction.type === "ManualFunding" ||
          transaction.type === "AutomaticFunding"
      )
      .reduce((sum, transaction) => sum + (transaction.amount || 0), 0);

    // Calculate Total Data Sold
    const totalDataSold = transactions
      .filter((transaction) => transaction.type === "DataTransaction")
      .reduce(
        (sum, transaction) => sum + parseFloat(transaction.plansize || 0),
        0
      );

    return NextResponse.json({
      walletBalance: user.accountBalance || 0,
      totalFunding: totalFunding || 0,
      referralBonus: user.refererBonus || 0,
      totalDataSold: totalDataSold || 0,
    });
  } catch (error) {
    console.error("Error fetching analytics data:", error);
    return NextResponse.json(
      { error: "Failed to fetch analytics data" },
      { status: 500 }
    );
  }
}
