const { PrismaClient } = require('@prisma/client')
const prisma = new PrismaClient()

// Helper function to generate commission invoices automatically
async function generateCommissionInvoices(generateForAll = false) {
  try {
    const currentDate = new Date()
    const currentDay = currentDate.getDate()

    // Find all owners or only those whose commission due day matches today
    const ownerWhere = {
      role: 'owner',
      deletedAt: null,
    }

    if (!generateForAll) {
      ownerWhere.commissionDueDay = currentDay
    }

    const owners = await prisma.user.findMany({
      where: ownerWhere,
      include: {
        ownedProperties: {
          where: { deletedAt: null },
          include: {
            units: {
              where: { deletedAt: null },
              include: {
                tenants: {
                  where: {
                    status: 'active',
                    deletedAt: null
                  }
                }
              }
            }
          }
        }
      }
    })

    const generatedInvoices = []

    for (const owner of owners) {
      for (const property of owner.ownedProperties) {
        // Calculate total monthly income from active tenants for this property
        let totalMonthlyIncome = 0
        property.units.forEach(unit => {
          unit.tenants.forEach(tenant => {
            totalMonthlyIncome += Number(tenant.monthlyRent)
          })
        })

        if (totalMonthlyIncome === 0) continue

        const commissionRate = Number(owner.commissionRate) || 10
        const commissionAmount = (totalMonthlyIncome * commissionRate) / 100

        // Check if invoice already exists for this property and month
        const currentMonth = currentDate.getMonth()
        const currentYear = currentDate.getFullYear()

        const existingInvoice = await prisma.commissionInvoice.findFirst({
          where: {
            propertyId: property.id,
            periodStart: {
              gte: new Date(currentYear, currentMonth, 1),
              lt: new Date(currentYear, currentMonth + 1, 1)
            }
          }
        })

        if (existingInvoice) continue

        // Generate invoice number - unique per property and period
        const invoiceNumber = `COM-${currentYear}${String(currentMonth + 1).padStart(2, '0')}-${property.id.slice(-6).toUpperCase()}-${String(currentDay).padStart(2, '0')}`

        // Create commission invoice
        const invoice = await prisma.commissionInvoice.create({
          data: {
            invoiceNumber,
            propertyId: property.id,
            companyId: owner.companyId,
            periodStart: new Date(currentYear, currentMonth, 1),
            periodEnd: new Date(currentYear, currentMonth + 1, 0),
            totalRentCollected: totalMonthlyIncome,
            commissionRate,
            commissionAmount,
            dueDate: new Date(currentYear, currentMonth, owner.commissionDueDay),
            status: 'pending'
          }
        })

        generatedInvoices.push(invoice)
      }
    }

    console.log(`Generated ${generatedInvoices.length} commission invoices`)
    return generatedInvoices
  } catch (error) {
    console.error('Error generating commission invoices:', error)
    return []
  }
}

// Run the function
generateCommissionInvoices()
  .then(() => {
    console.log('Commission invoice generation completed')
    process.exit(0)
  })
  .catch((error) => {
    console.error('Failed to generate commission invoices:', error)
    process.exit(1)
  })
  .finally(async () => {
    await prisma.$disconnect()
  })