import { NextResponse } from 'next/server';
import { prisma } from '@/lib/db';
import { getCurrentAdmin } from '@/lib/admin-auth';

export const runtime = 'nodejs';

export async function GET(request: Request) {
  try {
    const admin = await getCurrentAdmin(request as any);
    if (!admin) {
      return NextResponse.json(
        { error: 'Unauthorized' },
        { status: 401 }
      );
    }

    // Get date ranges
    const now = new Date();
    const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
    const yesterday = new Date(today.getTime() - 24 * 60 * 60 * 1000);
    const lastWeek = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000);

    // Parallel queries for better performance
    const [
      totalUsers,
      usersToday,
      usersYesterday,
      dailyActiveUsers,
      conversationsToday,
      conversationsYesterday,
      prayerRequestsToday,
      prayerRequestsYesterday,
      totalConversations,
      totalPrayerRequests
    ] = await Promise.all([
      // Total users
      prisma.user.count(),

      // Users created today
      prisma.user.count({
        where: {
          createdAt: {
            gte: today
          }
        }
      }),

      // Users created yesterday
      prisma.user.count({
        where: {
          createdAt: {
            gte: yesterday,
            lt: today
          }
        }
      }),

      // Daily active users (logged in today)
      prisma.user.count({
        where: {
          lastLoginAt: {
            gte: today
          }
        }
      }),

      // AI conversations today
      prisma.chatConversation.count({
        where: {
          createdAt: {
            gte: today
          }
        }
      }),

      // AI conversations yesterday
      prisma.chatConversation.count({
        where: {
          createdAt: {
            gte: yesterday,
            lt: today
          }
        }
      }),

      // Prayer requests today
      prisma.prayerRequest.count({
        where: {
          createdAt: {
            gte: today
          }
        }
      }),

      // Prayer requests yesterday
      prisma.prayerRequest.count({
        where: {
          createdAt: {
            gte: yesterday,
            lt: today
          }
        }
      }),

      // Total conversations
      prisma.chatConversation.count(),

      // Total prayer requests
      prisma.prayerRequest.count()
    ]);

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

    const userGrowthChange = calculateChange(usersToday, usersYesterday);
    const conversationChange = calculateChange(conversationsToday, conversationsYesterday);
    const prayerChange = calculateChange(prayerRequestsToday, prayerRequestsYesterday);

    return NextResponse.json({
      totalUsers,
      dailyActiveUsers,
      conversationsToday,
      prayerRequestsToday,
      userGrowthChange,
      conversationChange,
      prayerChange,
      totalConversations,
      totalPrayerRequests,
      usersToday,
      usersYesterday
    });

  } catch (error) {
    console.error('Admin overview stats error:', error);
    return NextResponse.json(
      { error: 'Server error' },
      { status: 500 }
    );
  }
}