import { db } from '@/lib/db'
import { NextRequest, NextResponse } from 'next/server'

export async function GET(_request: NextRequest) {
  try {
    // User stats by status
    const userStatusCounts = await db.user.groupBy({
      by: ['status'],
      _count: true,
    })

    const userStatusMap: Record<string, number> = {}
    for (const item of userStatusCounts) {
      userStatusMap[item.status] = item._count
    }

    // User stats by role
    const userRoleCounts = await db.user.groupBy({
      by: ['role'],
      _count: true,
    })

    const userRoleMap: Record<string, number> = {}
    for (const item of userRoleCounts) {
      userRoleMap[item.role] = item._count
    }

    const totalUsers = Object.values(userStatusMap).reduce((a, b) => a + b, 0)

    // Subscription stats
    const subscriptionStatusCounts = await db.subscription.groupBy({
      by: ['status'],
      _count: true,
    })

    const subscriptionStatusMap: Record<string, number> = {}
    for (const item of subscriptionStatusCounts) {
      subscriptionStatusMap[item.status] = item._count
    }

    const activeSubscriptions = subscriptionStatusMap['ACTIVE'] || 0

    // Revenue stats
    const invoiceStats = await db.invoice.aggregate({
      _sum: { totalAmount: true, paidAmount: true },
    })

    const totalRevenue = invoiceStats._sum.paidAmount || 0
    const totalBilled = invoiceStats._sum.totalAmount || 0

    // Invoice status counts
    const invoiceStatusCounts = await db.invoice.groupBy({
      by: ['status'],
      _count: true,
      _sum: { totalAmount: true },
    })

    const invoiceBreakdown: Record<string, { count: number; amount: number }> = {}
    for (const item of invoiceStatusCounts) {
      invoiceBreakdown[item.status] = {
        count: item._count,
        amount: item._sum.totalAmount || 0,
      }
    }

    // Due/overdue invoices
    const now = new Date()
    const dueInvoices = await db.invoice.count({
      where: {
        status: { in: ['UNPAID', 'DUE', 'PARTIAL'] },
        dueDate: { lt: now },
      },
    })

    // Payment stats - this month
    const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1)
    const thisMonthPayments = await db.payment.aggregate({
      where: {
        status: 'PAID',
        createdAt: { gte: startOfMonth },
      },
      _sum: { amount: true },
      _count: true,
    })

    // Ticket stats
    const ticketStatusCounts = await db.ticket.groupBy({
      by: ['status'],
      _count: true,
    })

    const ticketStatusMap: Record<string, number> = {}
    for (const item of ticketStatusCounts) {
      ticketStatusMap[item.status] = item._count
    }

    const openTickets = (ticketStatusMap['OPEN'] || 0) + (ticketStatusMap['IN_PROGRESS'] || 0)

    // OLT/ONU stats
    const oltCount = await db.oLTDevice.count({ where: { status: 'ONLINE' } })
    const onuStatusCounts = await db.oNU.groupBy({
      by: ['status'],
      _count: true,
    })

    const onuStatusMap: Record<string, number> = {}
    for (const item of onuStatusCounts) {
      onuStatusMap[item.status] = item._count
    }

    // Plan stats
    const activePlans = await db.plan.count({ where: { isActive: true } })

    // Area count
    const areaCount = await db.area.count()

    // Reseller count
    const resellerCount = await db.reseller.count()

    // Recent activity (last 5 invoices)
    const recentInvoices = await db.invoice.findMany({
      take: 5,
      orderBy: { createdAt: 'desc' },
      include: {
        user: { select: { id: true, name: true } },
      },
    })

    return NextResponse.json({
      success: true,
      data: {
        users: {
          total: totalUsers,
          byStatus: userStatusMap,
          byRole: userRoleMap,
          active: userStatusMap['ACTIVE'] || 0,
          expired: userStatusMap['EXPIRED'] || 0,
          suspended: userStatusMap['SUSPENDED'] || 0,
          pending: userStatusMap['PENDING'] || 0,
        },
        subscriptions: {
          total: Object.values(subscriptionStatusMap).reduce((a, b) => a + b, 0),
          active: activeSubscriptions,
          byStatus: subscriptionStatusMap,
        },
        revenue: {
          total: totalRevenue,
          totalBilled,
          thisMonth: thisMonthPayments._sum.amount || 0,
          thisMonthTransactions: thisMonthPayments._count,
          unpaid: (totalBilled) - (totalRevenue),
        },
        invoices: {
          breakdown: invoiceBreakdown,
          dueOverdue: dueInvoices,
        },
        tickets: {
          total: Object.values(ticketStatusMap).reduce((a, b) => a + b, 0),
          open: openTickets,
          byStatus: ticketStatusMap,
        },
        network: {
          onlineOLTs: oltCount,
          onus: onuStatusMap,
          totalONUs: Object.values(onuStatusMap).reduce((a, b) => a + b, 0),
        },
        plans: {
          active: activePlans,
        },
        areas: {
          total: areaCount,
        },
        resellers: {
          total: resellerCount,
        },
        recentInvoices,
      },
    })
  } catch (error: unknown) {
    const message = error instanceof Error ? error.message : 'Internal server error'
    return NextResponse.json(
      { success: false, error: message },
      { status: 500 }
    )
  }
}
