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

export async function GET(
  _request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params

    const reseller = await db.reseller.findUnique({
      where: { id },
      include: {
        user: { select: { id: true, name: true, email: true, phone: true, status: true } },
        commissions: {
          include: {
            invoice: { select: { id: true, invoiceNumber: true, totalAmount: true } },
            user: { select: { id: true, name: true, email: true } },
          },
          orderBy: { createdAt: 'desc' },
          take: 20,
        },
        transactions: {
          orderBy: { createdAt: 'desc' },
          take: 20,
        },
        _count: {
          select: {
            clients: { where: { status: 'ACTIVE' } },
            commissions: true,
          },
        },
      },
    })

    if (!reseller) {
      return NextResponse.json(
        { success: false, error: 'Reseller not found' },
        { status: 404 }
      )
    }

    // Commission breakdown
    const commissionStats = await db.commission.groupBy({
      by: ['status'],
      where: { resellerId: id },
      _sum: { amount: true },
      _count: true,
    })

    return NextResponse.json({
      success: true,
      data: {
        ...reseller,
        commissionBreakdown: commissionStats,
      },
    })
  } catch (error: unknown) {
    const message = error instanceof Error ? error.message : 'Internal server error'
    return NextResponse.json(
      { success: false, error: message },
      { status: 500 }
    )
  }
}

export async function PUT(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params
    const body = await request.json()

    const existing = await db.reseller.findUnique({ where: { id } })
    if (!existing) {
      return NextResponse.json(
        { success: false, error: 'Reseller not found' },
        { status: 404 }
      )
    }

    const { createdAt, updatedAt, user, commissions, transactions, ...updateData } = body as Record<string, unknown>

    const reseller = await db.reseller.update({
      where: { id },
      data: updateData,
      include: {
        user: { select: { id: true, name: true, email: true } },
      },
    })

    return NextResponse.json({ success: true, data: reseller })
  } catch (error: unknown) {
    const message = error instanceof Error ? error.message : 'Internal server error'
    return NextResponse.json(
      { success: false, error: message },
      { status: 500 }
    )
  }
}
