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 method = searchParams.get('method')
    const invoiceId = searchParams.get('invoiceId')
    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 (method) where.method = method
    if (invoiceId) where.invoiceId = invoiceId
    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)
    }

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

    // Summary stats
    const summary = await db.payment.aggregate({
      _sum: { amount: true },
      _count: true,
    })

    return NextResponse.json({
      success: true,
      data: {
        payments,
        summary: {
          totalCollected: summary._sum.amount || 0,
          totalTransactions: 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 }
    )
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    const { invoiceId, userId, amount, method, transactionId, notes } = body

    if (!invoiceId || !amount) {
      return NextResponse.json(
        { success: false, error: 'invoiceId and amount are required' },
        { status: 400 }
      )
    }

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

    const payment = await db.payment.create({
      data: {
        invoiceId,
        userId: userId || invoice.userId,
        amount: parseFloat(amount),
        method: method || 'CASH',
        transactionId: transactionId || '',
        status: 'PAID',
        notes: notes || '',
      },
      include: {
        user: { select: { id: true, name: true, email: true } },
        invoice: { select: { id: true, invoiceNumber: true } },
      },
    })

    // Update invoice paid amount and status
    const newPaidAmount = invoice.paidAmount + parseFloat(amount)
    const newStatus = newPaidAmount >= invoice.totalAmount ? 'PAID' : newPaidAmount > 0 ? 'PARTIAL' : 'UNPAID'

    await db.invoice.update({
      where: { id: invoiceId },
      data: { paidAmount: newPaidAmount, status: newStatus },
    })

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