from django.core.management.base import BaseCommand, CommandError
from paymentlog.services import get_food_log_instance
from tenant.models import TenantRent
from paymentlog.models import PaymentLog
from django.db import transaction
from utils.services import current_date
import logging

logger = logging.getLogger(__name__)



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

    def handle(self, *args, **options):
        try:
            with transaction.atomic(): # type: ignore
                tenant_rents = list(TenantRent.objects.filter(food_due__lte=current_date(), meal__price_per_month__gt=0)) # type: ignore
                payment_logs = []
                for tenant_rent in tenant_rents:
                    log_instance = get_food_log_instance(tenant_rent)
                    if log_instance is not None:
                        payment_logs.append(log_instance)
                PaymentLog.objects.bulk_create(payment_logs) # type: ignore
        except Exception as e:
            logger.error(e)
            raise CommandError('Unable to generate the food log.')
