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 page = parseInt(searchParams.get('page') || '1')
    const limit = parseInt(searchParams.get('limit') || '20')
    const status = searchParams.get('status')
    const userId = searchParams.get('userId')
    const subscriptionId = searchParams.get('subscriptionId')
    const areaId = searchParams.get('areaId')
    const fromDate = searchParams.get('fromDate')
    const toDate = searchParams.get('toDate')

    const where: Record<string, unknown> = {}

    if (status) where.status = status
    if (userId) where.userId = userId
    if (subscriptionId) where.subscriptionId = subscriptionId
    if (fromDate || toDate) {
      where.createdAt = {}
      if (fromDate) (where.createdAt as Record<string, unknown>).gte = new Date(fromDate)
      if (toDate) (where.createdAt as Record<string, unknown>).lte = new Date(toDate)
    }
    if (areaId) {
      where.subscription = { plan: { areaId } }
    }

    const [invoices, total] = await Promise.all([
      db.invoice.findMany({
        where,
        include: {
          user: { select: { id: true, name: true, email: true, phone: true, area: true } },
          subscription: { include: { plan: true } },
          payments: true,
        },
        orderBy: { createdAt: 'desc' },
        skip: (page - 1) * limit,
        take: limit,
      }),
      db.invoice.count({ where }),
    ])

    // Summary stats
    const summary = await db.invoice.aggregate({
      _sum: { totalAmount: true, paidAmount: true },
      _count: true,
    })

    return NextResponse.json({
      success: true,
      data: {
        invoices,
        summary: {
          totalAmount: summary._sum.totalAmount || 0,
          totalPaid: summary._sum.paidAmount || 0,
          totalUnpaid: (summary._sum.totalAmount || 0) - (summary._sum.paidAmount || 0),
          totalInvoices: summary._count,
        },
        pagination: {
          page,
          limit,
          total,
          totalPages: Math.ceil(total / limit),
        },
      },
    })
  } catch (error: unknown) {
    const message = error instanceof Error ? error.message : 'Internal server error'
    return NextResponse.json(
      { success: false, error: message },
      { status: 500 }
    )
  }
}
