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 period = searchParams.get('period') || 'monthly' // daily, monthly
    const months = parseInt(searchParams.get('months') || '12')

    const now = new Date()
    const startDate = new Date(now.getFullYear(), now.getMonth() - months + 1, 1)

    if (period === 'daily') {
      // Last 30 days revenue
      const dailyStart = new Date(now)
      dailyStart.setDate(dailyStart.getDate() - 30)
      dailyStart.setHours(0, 0, 0, 0)

      const payments = await db.payment.findMany({
        where: {
          status: 'PAID',
          createdAt: { gte: dailyStart },
        },
        select: {
          amount: true,
          createdAt: true,
        },
        orderBy: { createdAt: 'asc' },
      })

      // Group by date
      const dailyMap: Record<string, number> = {}
      for (let i = 0; i <= 30; i++) {
        const d = new Date(dailyStart)
        d.setDate(d.getDate() + i)
        const key = d.toISOString().split('T')[0]
        dailyMap[key] = 0
      }

      for (const payment of payments) {
        const key = payment.createdAt.toISOString().split('T')[0]
        if (dailyMap[key] !== undefined) {
          dailyMap[key] += payment.amount
        }
      }

      const dailyData = Object.entries(dailyMap).map(([date, amount]) => ({
        date,
        amount,
      }))

      return NextResponse.json({
        success: true,
        data: {
          period: 'daily',
          data: dailyData,
          total: dailyData.reduce((sum, d) => sum + d.amount, 0),
        },
      })
    }

    // Monthly revenue
    const monthlyData: Array<{ month: string; year: number; revenue: number; invoices: 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)

      const monthPayments = await db.payment.aggregate({
        where: {
          status: 'PAID',
          createdAt: { gte: monthStart, lte: monthEnd },
        },
        _sum: { amount: true },
        _count: true,
      })

      const monthInvoices = await db.invoice.aggregate({
        where: {
          createdAt: { gte: monthStart, lte: monthEnd },
        },
        _sum: { totalAmount: true },
        _count: true,
      })

      monthlyData.push({
        month: monthStart.toLocaleString('default', { month: 'short' }),
        year: monthStart.getFullYear(),
        revenue: monthPayments._sum.amount || 0,
        invoices: monthInvoices._count,
      })
    }

    const totalRevenue = monthlyData.reduce((sum, m) => sum + m.revenue, 0)

    // Calculate growth percentage
    let growthPercent = 0
    if (monthlyData.length >= 2) {
      const current = monthlyData[monthlyData.length - 1].revenue
      const previous = monthlyData[monthlyData.length - 2].revenue
      if (previous > 0) {
        growthPercent = ((current - previous) / previous) * 100
      }
    }

    return NextResponse.json({
      success: true,
      data: {
        period: 'monthly',
        data: monthlyData,
        totalRevenue,
        growthPercent: Math.round(growthPercent * 100) / 100,
      },
    })
  } catch (error: unknown) {
    const message = error instanceof Error ? error.message : 'Internal server error'
    return NextResponse.json(
      { success: false, error: message },
      { status: 500 }
    )
  }
}
