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

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url)
    const months = parseInt(searchParams.get('months') || '12')

    const now = new Date()
    const monthlyData: Array<{ month: string; year: number; total: number; active: number; expired: number; newUsers: number }> = []

    for (let i = months - 1; i >= 0; i--) {
      const monthStart = new Date(now.getFullYear(), now.getMonth() - i, 1)
      const monthEnd = new Date(now.getFullYear(), now.getMonth() - i + 1, 0, 23, 59, 59, 999)

      // New users this month
      const newUsers = await db.user.count({
        where: {
          createdAt: { gte: monthStart, lte: monthEnd },
        },
      })

      // User status at end of month (using current status as approximation)
      const activeUsers = await db.user.count({
        where: {
          status: 'ACTIVE',
          createdAt: { lte: monthEnd },
        },
      })

      const expiredUsers = await db.user.count({
        where: {
          status: 'EXPIRED',
          createdAt: { lte: monthEnd },
        },
      })

      const totalUsers = await db.user.count({
        where: {
          createdAt: { lte: monthEnd },
        },
      })

      monthlyData.push({
        month: monthStart.toLocaleString('default', { month: 'short' }),
        year: monthStart.getFullYear(),
        total: totalUsers,
        active: activeUsers,
        expired: expiredUsers,
        newUsers,
      })
    }

    // Calculate average monthly growth
    let avgMonthlyGrowth = 0
    if (monthlyData.length >= 2) {
      const growths: number[] = []
      for (let i = 1; i < monthlyData.length; i++) {
        const prev = monthlyData[i - 1].total
        const curr = monthlyData[i].total
        if (prev > 0) {
          growths.push(((curr - prev) / prev) * 100)
        }
      }
      if (growths.length > 0) {
        avgMonthlyGrowth = growths.reduce((a, b) => a + b, 0) / growths.length
      }
    }

    return NextResponse.json({
      success: true,
      data: {
        data: monthlyData,
        avgMonthlyGrowthPercent: Math.round(avgMonthlyGrowth * 100) / 100,
        totalNewUsers: monthlyData.reduce((sum, m) => sum + m.newUsers, 0),
      },
    })
  } catch (error: unknown) {
    const message = error instanceof Error ? error.message : 'Internal server error'
    return NextResponse.json(
      { success: false, error: message },
      { status: 500 }
    )
  }
}
