from django.core.management.base import BaseCommand, CommandError
from paymentlog.services import get_rent_log_instance
from django.db import transaction
from paymentlog.models import PaymentLog
from paymentlog.services import get_tenants_with_rent_due
from utils.services import current_date
import logging


logger = logging.getLogger(__name__)

class Command(BaseCommand):
    help = "Creates the rent logs for existing tenants if the current date is their due_date or a past due date"

    def handle(self, *args, **options):
        try:
            with transaction.atomic(): # type: ignore
                date = current_date()
                tenant_rents = get_tenants_with_rent_due(date)
                payment_logs = []
                for rent_info in tenant_rents:
                    log = get_rent_log_instance(rent_info, date) # type: ignore
                    if log is not None:
                        payment_logs.append(log)

                PaymentLog.objects.bulk_create(payment_logs) # type: ignore
        except Exception as e:
            logger.error(e)
            raise CommandError('Something went wrong while generating rent logs.')
