from django.core.management.base import BaseCommand
from django.utils import timezone
from tracking.models import Vehicle, MaintenanceLog
from django.core.mail import send_mail

class Command(BaseCommand):
    help = 'Check for vehicles due for maintenance and send alerts'

    def handle(self, *args, **kwargs):
        now = timezone.now()
        vehicles = Vehicle.objects.all()
        for vehicle in vehicles:
            last_maintenance = MaintenanceLog.objects.filter(vehicle=vehicle).order_by('-date').first()
            if last_maintenance and (now - last_maintenance.date).days > 180:
                # Send email alert
                send_mail(
                    'Maintenance Alert',
                    f'Vehicle {vehicle.license_plate} is due for maintenance.',
                    'from@example.com',
                    ['to@example.com'],
                )
                self.stdout.write(self.style.SUCCESS(f'Sent maintenance alert for vehicle {vehicle.license_plate}'))
