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 [resellers, total] = await Promise.all([
      db.reseller.findMany({
        include: {
          user: { select: { id: true, name: true, email: true, phone: true, status: true } },
          _count: {
            select: {
              clients: { where: { status: 'ACTIVE' } },
              commissions: { where: { status: 'PENDING' } },
            },
          },
        },
        orderBy: { createdAt: 'desc' },
        skip: (page - 1) * limit,
        take: limit,
      }),
      db.reseller.count(),
    ])

    // Get commission summaries for each reseller
    const resellersWithStats = await Promise.all(
      resellers.map(async (reseller) => {
        const commissionStats = await db.commission.aggregate({
          where: { resellerId: reseller.id },
          _sum: { amount: true },
          _count: true,
        })

        const pendingCommissions = await db.commission.aggregate({
          where: { resellerId: reseller.id, status: 'PENDING' },
          _sum: { amount: true },
        })

        const paidCommissions = await db.commission.aggregate({
          where: { resellerId: reseller.id, status: 'PAID' },
          _sum: { amount: true },
        })

        return {
          ...reseller,
          totalCommission: commissionStats._sum.amount || 0,
          totalTransactions: commissionStats._count,
          pendingCommission: pendingCommissions._sum.amount || 0,
          paidCommission: paidCommissions._sum.amount || 0,
        }
      })
    )

    return NextResponse.json({
      success: true,
      data: {
        resellers: resellersWithStats,
        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 }
    )
  }
}
