// pages/api/referral/details.ts
import { NextRequest, NextResponse } from "next/server";
import { getServerSession } from "next-auth";
import { authOptions } from "@/auth"; // Ensure this path is correct
import dbConnect from "@/lib/connectdb";
import { User, ReferralDeposit } from "@/models/user";
import { image } from "html2canvas/dist/types/css/types/image";

export async function GET(req: NextRequest) {
  try {
    const session = await getServerSession(authOptions);

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

    await dbConnect().catch(() => {
      throw new Error("Database connection failed.");
    });

    const user = await User.findOne({ email: session.user?.email })
      .populate({
        path: "referrals",
        populate: { path: "referredId", select: "name email image lastLogin" },
      })
      .exec();

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

    if (!user.referrals || user.referrals.length === 0) {
      return NextResponse.json(
        { message: "No referrals found for this user." },
        { status: 200 }
      );
    }

    const referralDetails = user.referrals.map((ref: any) => ({
      name: ref.referredId?.name || "Unknown",
      email: ref.referredId?.email || "Unknown",
      image: ref.referredId?.image || "No image",
      lastLogin: ref.referredId?.lastLogin || "No login data",
    }));

    const totalDeposits = await ReferralDeposit.aggregate([
      { $match: { referredId: user._id } },
      { $group: { _id: null, total: { $sum: "$referrerCredit" } } },
    ]).catch(() => {
      throw new Error("Failed to fetch referral deposit data.");
    });

    return NextResponse.json(
      {
        referralDetails,
        totalReferrals: user.referrals.length,
        totalDeposits: totalDeposits[0]?.total || 0,
      },
      { status: 200 }
    );
  } catch (error: any) {
    console.error("Error in referral details API:", error.message);

    return NextResponse.json(
      {
        error:
          error.message || "Internal Server Error. Please try again later.",
      },
      { status: 500 }
    );
  }
}
