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

export async function POST(_request: NextRequest) {
  try {
    const now = new Date()

    // Find all unpaid invoices past their due date
    const overdueInvoices = await db.invoice.findMany({
      where: {
        status: { in: ['UNPAID', 'DUE', 'PARTIAL'] },
        dueDate: { lt: now },
        paidAmount: { lt: 1 }, // Only truly unpaid (allow small floating point)
      },
      include: {
        user: true,
        subscription: {
          include: { plan: true },
        },
      },
    })

    const results = {
      processed: 0,
      suspended: 0,
      warningsIssued: 0,
      errors: [] as string[],
      details: [] as Array<{
        userId: string
        userName: string
        invoiceId: string
        invoiceNumber: string
        totalAmount: number
        dueDate: string
        action: string
      }>,
    }

    // Track which users have been processed to avoid duplicate actions
    const processedUsers = new Set<string>()

    for (const invoice of overdueInvoices) {
      try {
        if (processedUsers.has(invoice.userId)) {
          results.processed++
          continue
        }

        // Calculate how many days overdue
        const daysOverdue = Math.floor(
          (now.getTime() - invoice.dueDate.getTime()) / (1000 * 60 * 60 * 24)
        )

        if (daysOverdue >= 30) {
          // Suspend user after 30 days overdue
          await db.user.update({
            where: { id: invoice.userId },
            data: { status: 'SUSPENDED' },
          })

          // Also suspend their active subscriptions
          await db.subscription.updateMany({
            where: {
              userId: invoice.userId,
              status: 'ACTIVE',
            },
            data: { status: 'SUSPENDED' },
          })

          // Mark invoice as DUE
          await db.invoice.update({
            where: { id: invoice.id },
            data: { status: 'DUE' },
          })

          results.suspended++
          results.details.push({
            userId: invoice.userId,
            userName: invoice.user.name,
            invoiceId: invoice.id,
            invoiceNumber: invoice.invoiceNumber,
            totalAmount: invoice.totalAmount,
            dueDate: invoice.dueDate.toISOString(),
            action: 'SUSPENDED',
          })
        } else if (daysOverdue >= 15) {
          // Warning stage - just mark as DUE
          await db.invoice.update({
            where: { id: invoice.id },
            data: { status: 'DUE' },
          })

          results.warningsIssued++
          results.details.push({
            userId: invoice.userId,
            userName: invoice.user.name,
            invoiceId: invoice.id,
            invoiceNumber: invoice.invoiceNumber,
            totalAmount: invoice.totalAmount,
            dueDate: invoice.dueDate.toISOString(),
            action: 'WARNING',
          })
        }

        processedUsers.add(invoice.userId)
        results.processed++
      } catch (err: unknown) {
        const errorMessage = err instanceof Error ? err.message : 'Unknown error'
        results.errors.push(`Invoice ${invoice.id}: ${errorMessage}`)
      }
    }

    return NextResponse.json({
      success: true,
      data: results,
      message: `Processed ${results.processed} invoices. Suspended: ${results.suspended}, Warnings: ${results.warningsIssued}`,
    })
  } catch (error: unknown) {
    const message = error instanceof Error ? error.message : 'Internal server error'
    return NextResponse.json(
      { success: false, error: message },
      { status: 500 }
    )
  }
}
