import { NextRequest, NextResponse } from "next/server";
import { authOptions } from "@/app/api/auth/[...nextauth]/auth-options";
import { getServerSession } from "next-auth";
import db from "@/lib/db";
import { UserRole } from "@prisma/client";
import { getLogger } from "@/utils/logger";

const logger = getLogger("/api/admin/dashboard");


export async function GET(req: NextRequest) {

  try {

    const session = await getServerSession(authOptions);

    if (!session || session.user.role !== UserRole.ADMIN) {
      logger.warn("Forbidden", { userRole: session?.user.role });
      return new NextResponse("Forbidden", { status: 403 });
    }

    const totalOrdersCount = await db.orders.count({})

    const totalCustomersCount = await db.user.count({
      where: {
        role: UserRole.USER
      }
    })

    const totalRevenue = await db.orders.aggregate({
      where: {
        shipment_details: {
          is_delivered: true
        }
      },
      _sum: {
        order_total_amount: true
      }
    })

    const totalCouponsCount = await db.coupon.count({})

    const latestOrders = await db.orders.findMany({
      orderBy: {
        order_date: 'desc'
      },
      take: 7,
      include: {
        shipment_details: true,

      }

    })

    const thisMonthOrdersCount = await db.orders.count({
      where: {
        order_date: {
          gte: new Date(new Date().getFullYear(), new Date().getMonth(), 1),
          lte: new Date()
        }
      }
    })

    const thisMonthRevenue = await db.orders.aggregate({
      where: {
        AND: {
          order_date: {
            gte: new Date(new Date().getFullYear(), new Date().getMonth(), 1),
            lte: new Date()
          },
          shipment_details: {
            is_delivered: true
          }
        }
      },
      _sum: {
        order_total_amount: true
      }
    })

    const thisMonthReviewsCount = await db.review.count({
      where: {
        created_on: {
          gte: new Date(new Date().getFullYear(), new Date().getMonth(), 1),
          lte: new Date()
        }
      }
    })

    const lastMonthOrdersCount = await db.orders.count({
      where: {
        order_date: {
          gte: new Date(new Date().getFullYear(), new Date().getMonth() - 1, 1),
          lte: new Date(new Date().getFullYear(), new Date().getMonth(), 0)
        }
      }
    })

    const lastMonthRevenue = await db.orders.aggregate({
      where: {
        AND: {
          order_date: {
            gte: new Date(new Date().getFullYear(), new Date().getMonth() - 1, 1),
            lte: new Date(new Date().getFullYear(), new Date().getMonth(), 0)

          },
          shipment_details: {
            is_delivered: true
          }
        }
      },
      _sum: {
        order_total_amount: true
      }
    })

    console.log(`This month revenue = ${thisMonthRevenue}`)

    const thisMonthCustomersCount = await db.user.count({
      where: {
        role: UserRole.USER,
        created_on: {
          gte: new Date(new Date().getFullYear(), new Date().getMonth(), 1),
          lte: new Date()
        }
      }
    })

    const lastMonthCustomersCount = await db.user.count({
      where: {
        role: UserRole.USER,
        created_on: {
          gte: new Date(new Date().getFullYear(), new Date().getMonth() - 1, 1),
          lte: new Date(new Date().getFullYear(), new Date().getMonth(), 0)
        }
      }
    })

    const recentReviews = await db.review.findMany({
      orderBy: {
        created_on: 'desc'
      },
      take: 5,
      include: {
        profile: true,
        variant: true

      }
    })

    return NextResponse.json({
      mssg: "Hello from admin dashboard", totalOrdersCount, totalCustomersCount,
      totalRevenue, totalCouponsCount, latestOrders, recentReviews, thisMonthOrdersCount,
      thisMonthRevenue, thisMonthReviewsCount, thisMonthCustomersCount, lastMonthOrdersCount,
      lastMonthRevenue, lastMonthCustomersCount
    }, { status: 200 });

    // return NextResponse.json({data: categories}, {status: 200})
  } catch (error: any) {
    logger.error("Failed to fetch dashboard data", {
      error: error?.config?.data ?? error?.message ?? "Unknown error"
    });

    return new NextResponse("Internal server Error", { status: 500 });
  }
}
