#!/usr/bin/env node

/**
 * Script to send due date reminders for rent invoices
 * This script can be run manually or set up as a cron job
 *
 * Usage:
 * node scripts/send-due-reminders.js [companyId]
 *
 * If no companyId is provided, it will process all companies
 */

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

const transporter = nodemailer.createTransporter({
  host: process.env.SMTP_HOST,
  port: parseInt(process.env.SMTP_PORT || '587'),
  secure: false,
  auth: {
    user: process.env.SMTP_USER,
    pass: process.env.SMTP_PASS,
  },
})

async function sendDueDateReminder(tenantEmail, tenantName, invoiceNumber, amount, dueDate, daysUntilDue, companyName) {
  const subject = `Rent Payment Due Soon - ${daysUntilDue} days remaining`
  const html = `
    <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
      <h2 style="color: #ff6b35;">Rent Payment Reminder</h2>
      <p>Dear ${tenantName},</p>
      <p>This is a friendly reminder that your rent payment is due soon.</p>
      <div style="background-color: #fff3cd; padding: 20px; margin: 20px 0; border-radius: 5px; border-left: 4px solid #ffc107;">
        <p><strong>Invoice Number:</strong> ${invoiceNumber}</p>
        <p><strong>Amount Due:</strong> UGX ${amount.toLocaleString()}</p>
        <p><strong>Due Date:</strong> ${dueDate.toLocaleDateString('en-US', {
          weekday: 'long',
          year: 'numeric',
          month: 'long',
          day: 'numeric'
        })}</p>
        <p><strong>Days Remaining:</strong> ${daysUntilDue}</p>
      </div>
      <p>Please make your payment before the due date to avoid late fees.</p>
      <p>You can make payment through your tenant dashboard or contact your property manager.</p>
      <p>Thank you for your prompt attention to this matter.</p>
      <p>Best regards,<br>${companyName} Team</p>
    </div>
  `

  const mailOptions = {
    from: `"${process.env.FROM_NAME}" <${process.env.FROM_EMAIL}>`,
    to: tenantEmail,
    subject,
    html,
  }

  return transporter.sendMail(mailOptions)
}

async function sendOverdueNotification(tenantEmail, tenantName, invoiceNumber, amount, dueDate, daysOverdue, companyName) {
  const subject = `Overdue Rent Payment - Immediate Attention Required`
  const html = `
    <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
      <h2 style="color: #dc3545;">Overdue Rent Payment Notice</h2>
      <p>Dear ${tenantName},</p>
      <p>We noticed that your rent payment is overdue. Please attend to this matter immediately.</p>
      <div style="background-color: #f8d7da; padding: 20px; margin: 20px 0; border-radius: 5px; border-left: 4px solid #dc3545;">
        <p><strong>Invoice Number:</strong> ${invoiceNumber}</p>
        <p><strong>Amount Due:</strong> UGX ${amount.toLocaleString()}</p>
        <p><strong>Original Due Date:</strong> ${dueDate.toLocaleDateString('en-US', {
          weekday: 'long',
          year: 'numeric',
          month: 'long',
          day: 'numeric'
        })}</p>
        <p><strong>Days Overdue:</strong> ${daysOverdue}</p>
      </div>
      <p>Late fees may apply. Please contact your property manager immediately to arrange payment.</p>
      <p>You can make payment through your tenant dashboard.</p>
      <p>Best regards,<br>${companyName} Team</p>
    </div>
  `

  const mailOptions = {
    from: `"${process.env.FROM_NAME}" <${process.env.FROM_EMAIL}>`,
    to: tenantEmail,
    subject,
    html,
  }

  return transporter.sendMail(mailOptions)
}

async function sendDueReminders(companyId = null) {
  console.log('📧 Starting due date reminder sending...')

  try {
    // Get companies to process
    let companies = []
    if (companyId) {
      const company = await prisma.company.findUnique({
        where: { id: companyId },
        select: { id: true, name: true }
      })
      if (!company) {
        console.error(`❌ Company with ID ${companyId} not found`)
        return
      }
      companies = [company]
    } else {
      companies = await prisma.company.findMany({
        select: { id: true, name: true }
      })
    }

    console.log(`📊 Processing ${companies.length} companies`)

    const now = new Date()
    let totalReminders = 0
    let totalOverdue = 0

    for (const company of companies) {
      console.log(`\n🏢 Processing company: ${company.name} (${company.id})`)

      // Send reminders for invoices due in 7 days
      const reminderDate = new Date(now)
      reminderDate.setDate(now.getDate() + 7)

      const upcomingInvoices = await prisma.rentInvoice.findMany({
        where: {
          companyId: company.id,
          status: 'pending',
          dueDate: {
            gte: now,
            lte: reminderDate
          }
        },
        include: {
          tenant: {
            select: {
              firstName: true,
              lastName: true,
              email: true
            }
          }
        }
      })

      console.log(`📅 Found ${upcomingInvoices.length} invoices due within 7 days`)

      for (const invoice of upcomingInvoices) {
        if (invoice.tenant.email) {
          const daysUntilDue = Math.ceil((invoice.dueDate.getTime() - now.getTime()) / (1000 * 60 * 60 * 24))
          try {
            await sendDueDateReminder(
              invoice.tenant.email,
              `${invoice.tenant.firstName} ${invoice.tenant.lastName}`,
              invoice.invoiceNumber,
              parseFloat(invoice.amount.toString()),
              invoice.dueDate,
              daysUntilDue,
              company.name
            )
            console.log(`📧 Reminder sent to ${invoice.tenant.email} for invoice ${invoice.invoiceNumber}`)
            totalReminders++
          } catch (emailError) {
            console.error(`❌ Failed to send reminder to ${invoice.tenant.email}:`, emailError.message)
          }
        }
      }

      // Send overdue notifications for invoices past due date
      const overdueInvoices = await prisma.rentInvoice.findMany({
        where: {
          companyId: company.id,
          status: 'pending',
          dueDate: {
            lt: now
          }
        },
        include: {
          tenant: {
            select: {
              firstName: true,
              lastName: true,
              email: true
            }
          }
        }
      })

      console.log(`⚠️  Found ${overdueInvoices.length} overdue invoices`)

      for (const invoice of overdueInvoices) {
        if (invoice.tenant.email) {
          const daysOverdue = Math.floor((now.getTime() - invoice.dueDate.getTime()) / (1000 * 60 * 60 * 24))
          try {
            await sendOverdueNotification(
              invoice.tenant.email,
              `${invoice.tenant.firstName} ${invoice.tenant.lastName}`,
              invoice.invoiceNumber,
              parseFloat(invoice.amount.toString()),
              invoice.dueDate,
              daysOverdue,
              company.name
            )
            console.log(`📧 Overdue notice sent to ${invoice.tenant.email} for invoice ${invoice.invoiceNumber}`)
            totalOverdue++
          } catch (emailError) {
            console.error(`❌ Failed to send overdue notice to ${invoice.tenant.email}:`, emailError.message)
          }
        }
      }
    }

    console.log(`\n✅ Due reminders completed! Sent ${totalReminders} reminders and ${totalOverdue} overdue notices.`)

  } catch (error) {
    console.error('❌ Error sending due reminders:', error)
  } finally {
    await prisma.$disconnect()
  }
}

// Main execution
async function main() {
  const args = process.argv.slice(2)
  const companyId = args[0]

  await sendDueReminders(companyId)
}

// Run the script
main().catch(console.error)