import { NextRequest, NextResponse } from "next/server";
import { requireStaffAuth } from "@/lib/staff-auth";
import { prisma } from "@/lib/db";
import { contactSubmissionsAdapter } from "@/lib/adapters/contacts";
// Convex routing (WU-13): analytics queries are user-scoped; needs a global getDashboardOverview query.

export async function GET(request: NextRequest) {
  try {
    // Require staff authentication
    const user = await requireStaffAuth();

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

    // Get today's date range
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    const tomorrow = new Date(today);
    tomorrow.setDate(tomorrow.getDate() + 1);

    // Get yesterday's date range for comparison
    const yesterday = new Date(today);
    yesterday.setDate(yesterday.getDate() - 1);

    // Current time for active sessions
    const now = new Date();

    // Parallel fetch all metrics
    const [
      visitorsToday,
      visitorsYesterday,
      demosToday,
      demosYesterday,
      contactsToday,
      contactsYesterday,
      signupsToday,
      signupsYesterday,
      revenueToday,
      revenueYesterday,
      activeSessions,
      loginsToday,
      loginsYesterday,
      recentDemos,
      recentContacts,
      recentUsers,
    ] = await Promise.all([
      // Visitors
      prisma.site_visits.count({
        where: {
          createdAt: { gte: today, lt: tomorrow },
        },
      }),
      prisma.site_visits.count({
        where: {
          createdAt: { gte: yesterday, lt: today },
        },
      }),
      // Demos
      prisma.demo_bookings.count({
        where: {
          createdAt: { gte: today, lt: tomorrow },
        },
      }),
      prisma.demo_bookings.count({
        where: {
          createdAt: { gte: yesterday, lt: today },
        },
      }),
      // Contacts
      contactSubmissionsAdapter.count({
        where: {
          created_at: { gte: today, lt: tomorrow },
        },
      }),
      contactSubmissionsAdapter.count({
        where: {
          created_at: { gte: yesterday, lt: today },
        },
      }),
      // Signups
      prisma.users.count({
        where: {
          createdAt: { gte: today, lt: tomorrow },
          role: "CUSTOMER",
        },
      }),
      prisma.users.count({
        where: {
          createdAt: { gte: yesterday, lt: today },
          role: "CUSTOMER",
        },
      }),
      // Revenue (only for admin+)
      user.role !== "STAFF"
        ? prisma.payments.aggregate({
            where: {
              createdAt: { gte: today, lt: tomorrow },
              status: "succeeded",
            },
            _sum: { amount: true },
          })
        : Promise.resolve({ _sum: { amount: 0 } }),
      user.role !== "STAFF"
        ? prisma.payments.aggregate({
            where: {
              createdAt: { gte: yesterday, lt: today },
              status: "succeeded",
            },
            _sum: { amount: true },
          })
        : Promise.resolve({ _sum: { amount: 0 } }),
      // Active sessions (currently signed in users)
      prisma.user_sessions.count({
        where: {
          expiresAt: { gte: now },
        },
      }),
      // Logins today (unique users who created sessions today)
      prisma.user_sessions
        .groupBy({
          by: ["userId"],
          where: {
            createdAt: { gte: today, lt: tomorrow },
          },
        })
        .then((result) => result.length),
      // Logins yesterday
      prisma.user_sessions
        .groupBy({
          by: ["userId"],
          where: {
            createdAt: { gte: yesterday, lt: today },
          },
        })
        .then((result) => result.length),
      // Recent activity
      prisma.demo_bookings.findMany({
        where: {},
        orderBy: { createdAt: "desc" },
        take: 5,
        select: {
          id: true,
          fullName: true,
          email: true,
          createdAt: true,
        },
      }),
      contactSubmissionsAdapter.findMany({
        where: {},
        orderBy: { created_at: "desc" },
        take: 5,
        select: {
          id: true,
          name: true,
          email: true,
          created_at: true,
        },
      }),
      prisma.users.findMany({
        where: { role: "CUSTOMER" },
        orderBy: { createdAt: "desc" },
        take: 5,
        select: {
          id: true,
          name: true,
          email: true,
          createdAt: true,
        },
      }),
    ]);

    // Calculate percentage changes
    const calculateChange = (current: number, previous: number) => {
      if (previous === 0) return current > 0 ? 100 : 0;
      return Math.round(((current - previous) / previous) * 100);
    };

    // Transform recent contacts to use camelCase
    const transformedRecentContacts = recentContacts.map((contact) => ({
      id: contact.id,
      name: contact.name,
      email: contact.email,
      createdAt: contact.created_at,
    }));

    const response = {
      today: {
        visitors: visitorsToday,
        demos: demosToday,
        contacts: contactsToday,
        signups: signupsToday,
        revenue: (revenueToday._sum.amount || 0) / 100, // Convert cents to dollars
        activeSessions: activeSessions,
        logins: loginsToday,
      },
      comparison: {
        visitors: calculateChange(visitorsToday, visitorsYesterday),
        demos: calculateChange(demosToday, demosYesterday),
        contacts: calculateChange(contactsToday, contactsYesterday),
        signups: calculateChange(signupsToday, signupsYesterday),
        revenue: calculateChange(
          revenueToday._sum.amount || 0,
          revenueYesterday._sum.amount || 0,
        ),
        logins: calculateChange(loginsToday, loginsYesterday),
      },
      recentActivity: {
        demos: recentDemos,
        contacts: transformedRecentContacts,
        users: recentUsers,
      },
    };

    return NextResponse.json(response);
  } catch (error) {
    console.error("Dashboard overview error:", error);
    return NextResponse.json(
      { error: "Failed to fetch dashboard data" },
      { status: 500 },
    );
  }
}
