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 url = new URL(request.url);
    const period = url.searchParams.get('period') || '30'; // days
    const periodDays = parseInt(period);
    const startDate = new Date();
    startDate.setDate(startDate.getDate() - periodDays);

    // User statistics
    const totalUsers = await prisma.user.count();
    const newUsers = await prisma.user.count({
      where: {
        createdAt: {
          gte: startDate
        }
      }
    });
    const activeUsers = await prisma.user.count({
      where: {
        lastLoginAt: {
          gte: startDate
        }
      }
    });

    // Content statistics
    const totalPrayerRequests = await prisma.prayerRequest.count();
    const activePrayerRequests = await prisma.prayerRequest.count({
      where: { isActive: true }
    });
    const newPrayerRequests = await prisma.prayerRequest.count({
      where: {
        createdAt: {
          gte: startDate
        }
      }
    });

    // Prayer statistics
    const totalPrayers = await prisma.prayer.count();
    const newPrayers = await prisma.prayer.count({
      where: {
        createdAt: {
          gte: startDate
        }
      }
    });

    // Chat statistics
    const totalConversations = await prisma.chatConversation.count();
    const activeConversations = await prisma.chatConversation.count({
      where: { isActive: true }
    });
    const newConversations = await prisma.chatConversation.count({
      where: {
        createdAt: {
          gte: startDate
        }
      }
    });

    const totalMessages = await prisma.chatMessage.count();
    const newMessages = await prisma.chatMessage.count({
      where: {
        timestamp: {
          gte: startDate
        }
      }
    });

    // Bookmark statistics
    const totalBookmarks = await prisma.bookmark.count();
    const newBookmarks = await prisma.bookmark.count({
      where: {
        createdAt: {
          gte: startDate
        }
      }
    });

    // User role distribution
    const usersByRole = await prisma.user.groupBy({
      by: ['role'],
      _count: {
        role: true
      }
    });

    // Prayer request categories
    const prayersByCategory = await prisma.prayerRequest.groupBy({
      by: ['category'],
      _count: {
        category: true
      },
      where: {
        isActive: true
      }
    });

    // Top prayer requests by prayer count
    const topPrayerRequests = await prisma.prayerRequest.findMany({
      select: {
        id: true,
        title: true,
        category: true,
        prayerCount: true,
        author: true
      },
      where: {
        isActive: true
      },
      orderBy: {
        prayerCount: 'desc'
      },
      take: 10
    });

    // Recent activity (last 7 days daily breakdown)
    const last7Days = Array.from({ length: 7 }, (_, i) => {
      const date = new Date();
      date.setDate(date.getDate() - i);
      return date.toISOString().split('T')[0];
    }).reverse();

    const dailyActivity = await Promise.all(
      last7Days.map(async (date) => {
        const startOfDay = new Date(date + 'T00:00:00.000Z');
        const endOfDay = new Date(date + 'T23:59:59.999Z');

        const [newUsers, newPrayers, newConversations, newBookmarks] = await Promise.all([
          prisma.user.count({
            where: {
              createdAt: {
                gte: startOfDay,
                lte: endOfDay
              }
            }
          }),
          prisma.prayer.count({
            where: {
              createdAt: {
                gte: startOfDay,
                lte: endOfDay
              }
            }
          }),
          prisma.chatConversation.count({
            where: {
              createdAt: {
                gte: startOfDay,
                lte: endOfDay
              }
            }
          }),
          prisma.bookmark.count({
            where: {
              createdAt: {
                gte: startOfDay,
                lte: endOfDay
              }
            }
          })
        ]);

        return {
          date,
          newUsers,
          newPrayers,
          newConversations,
          newBookmarks
        };
      })
    );

    return NextResponse.json({
      period: periodDays,
      overview: {
        users: {
          total: totalUsers,
          new: newUsers,
          active: activeUsers
        },
        prayerRequests: {
          total: totalPrayerRequests,
          active: activePrayerRequests,
          new: newPrayerRequests
        },
        prayers: {
          total: totalPrayers,
          new: newPrayers
        },
        conversations: {
          total: totalConversations,
          active: activeConversations,
          new: newConversations
        },
        messages: {
          total: totalMessages,
          new: newMessages
        },
        bookmarks: {
          total: totalBookmarks,
          new: newBookmarks
        }
      },
      distributions: {
        usersByRole,
        prayersByCategory
      },
      topContent: {
        prayerRequests: topPrayerRequests
      },
      activity: {
        daily: dailyActivity
      }
    });

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