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

export const runtime = 'nodejs';

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

    const now = new Date();
    const last24Hours = new Date(now.getTime() - 24 * 60 * 60 * 1000);
    const lastHour = new Date(now.getTime() - 60 * 60 * 1000);
    const last15Minutes = new Date(now.getTime() - 15 * 60 * 1000);

    // Real-time activity counters
    const realTimeStats = {
      last15Minutes: {
        newUsers: await prisma.user.count({
          where: { createdAt: { gte: last15Minutes } }
        }),
        newPrayers: await prisma.prayer.count({
          where: { createdAt: { gte: last15Minutes } }
        }),
        newMessages: await prisma.chatMessage.count({
          where: { timestamp: { gte: last15Minutes } }
        }),
        newBookmarks: await prisma.bookmark.count({
          where: { createdAt: { gte: last15Minutes } }
        })
      },
      lastHour: {
        newUsers: await prisma.user.count({
          where: { createdAt: { gte: lastHour } }
        }),
        newPrayers: await prisma.prayer.count({
          where: { createdAt: { gte: lastHour } }
        }),
        newMessages: await prisma.chatMessage.count({
          where: { timestamp: { gte: lastHour } }
        }),
        newBookmarks: await prisma.bookmark.count({
          where: { createdAt: { gte: lastHour } }
        }),
        activeConversations: await prisma.chatConversation.count({
          where: {
            lastMessageAt: { gte: lastHour },
            isActive: true
          }
        })
      },
      last24Hours: {
        newUsers: await prisma.user.count({
          where: { createdAt: { gte: last24Hours } }
        }),
        newPrayers: await prisma.prayer.count({
          where: { createdAt: { gte: last24Hours } }
        }),
        newPrayerRequests: await prisma.prayerRequest.count({
          where: { createdAt: { gte: last24Hours } }
        }),
        newMessages: await prisma.chatMessage.count({
          where: { timestamp: { gte: last24Hours } }
        }),
        newConversations: await prisma.chatConversation.count({
          where: { createdAt: { gte: last24Hours } }
        }),
        newBookmarks: await prisma.bookmark.count({
          where: { createdAt: { gte: last24Hours } }
        })
      }
    };

    // Current online activity indicators
    const recentActivity = {
      activeUsers: await prisma.user.count({
        where: {
          lastLoginAt: { gte: lastHour }
        }
      }),
      recentConversations: await prisma.chatConversation.findMany({
        select: {
          id: true,
          title: true,
          lastMessageAt: true,
          user: {
            select: {
              name: true,
              email: true
            }
          }
        },
        where: {
          lastMessageAt: { gte: lastHour },
          isActive: true
        },
        orderBy: {
          lastMessageAt: 'desc'
        },
        take: 10
      }),
      recentPrayerRequests: await prisma.prayerRequest.findMany({
        select: {
          id: true,
          title: true,
          category: true,
          author: true,
          createdAt: true
        },
        where: {
          createdAt: { gte: last24Hours },
          isActive: true
        },
        orderBy: {
          createdAt: 'desc'
        },
        take: 10
      }),
      recentPrayers: await prisma.prayer.findMany({
        select: {
          id: true,
          createdAt: true,
          request: {
            select: {
              title: true,
              category: true
            }
          }
        },
        where: {
          createdAt: { gte: lastHour }
        },
        orderBy: {
          createdAt: 'desc'
        },
        take: 10
      })
    };

    // System health indicators
    const systemHealth = {
      totalUsers: await prisma.user.count(),
      totalPrayerRequests: await prisma.prayerRequest.count({ where: { isActive: true } }),
      totalActiveConversations: await prisma.chatConversation.count({ where: { isActive: true } }),
      pendingModerationRequests: await prisma.prayerRequest.count({ where: { isActive: false } }),
      timestamp: now.toISOString()
    };

    // Hourly breakdown for the last 24 hours
    const hourlyBreakdown = await Promise.all(
      Array.from({ length: 24 }, (_, i) => {
        const hour = new Date(now.getTime() - i * 60 * 60 * 1000);
        const hourStart = new Date(hour.getFullYear(), hour.getMonth(), hour.getDate(), hour.getHours(), 0, 0);
        const hourEnd = new Date(hour.getFullYear(), hour.getMonth(), hour.getDate(), hour.getHours(), 59, 59);

        return hourStart.toISOString().split('T')[1].substring(0, 5);
      }).reverse().map(async (time, index) => {
        const hourStart = new Date(now.getTime() - (23 - index) * 60 * 60 * 1000);
        hourStart.setMinutes(0, 0, 0);
        const hourEnd = new Date(hourStart.getTime() + 60 * 60 * 1000 - 1);

        const [users, prayers, messages, conversations] = await Promise.all([
          prisma.user.count({
            where: {
              createdAt: {
                gte: hourStart,
                lte: hourEnd
              }
            }
          }),
          prisma.prayer.count({
            where: {
              createdAt: {
                gte: hourStart,
                lte: hourEnd
              }
            }
          }),
          prisma.chatMessage.count({
            where: {
              timestamp: {
                gte: hourStart,
                lte: hourEnd
              }
            }
          }),
          prisma.chatConversation.count({
            where: {
              createdAt: {
                gte: hourStart,
                lte: hourEnd
              }
            }
          })
        ]);

        return {
          time,
          users,
          prayers,
          messages,
          conversations
        };
      })
    );

    return NextResponse.json({
      timestamp: now.toISOString(),
      stats: realTimeStats,
      activity: recentActivity,
      health: systemHealth,
      hourlyBreakdown
    });

  } catch (error) {
    console.error('Admin real-time analytics error:', error);
    return NextResponse.json(
      { error: 'Server error' },
      { status: 500 }
    );
  }
}