
from django.core.management.base import BaseCommand
from django.utils import timezone
from customers.models import Customer
from billing.models import ServicePeriod


class Command(BaseCommand):
    help = 'Fix incorrect customer statuses - one-time cleanup'
    
    def add_arguments(self, parser):
        parser.add_argument(
            '--dry-run',
            action='store_true',
            help='Run in dry-run mode without making changes',
        )
    
    def handle(self, *args, **options):
        dry_run = options['dry_run']
        
        self.stdout.write(
            self.style.SUCCESS(f'Fixing customer statuses at {timezone.now()}')
        )
        
        if dry_run:
            self.stdout.write(
                self.style.WARNING('Running in DRY-RUN mode - no changes will be made')
            )
        
        fixed_count = 0
        
        # 1. Fix customers without services but marked as active
        no_service_active = Customer.objects.filter(
            service__isnull=True,
            service_status='active'
        )
        
        self.stdout.write(f'Found {no_service_active.count()} customers without services but marked active')
        
        for customer in no_service_active:
            if not dry_run:
                customer.service_status = 'inactive'
                customer.save()
            self.stdout.write(f'{"Fixed" if not dry_run else "Would fix"}: {customer.customer_id} - {customer.display_name} (no service assigned)')
            fixed_count += 1
        
        # 2. Fix customers with expired services but still marked active
        expired_but_active = []
        active_customers = Customer.objects.filter(
            service__isnull=False,
            service_status='active'
        )
        
        for customer in active_customers:
            # Get the most recent service period
            latest_period = ServicePeriod.objects.filter(
                customer=customer
            ).order_by('-service_end').first()
            
            if latest_period and latest_period.is_expired:
                expired_but_active.append((customer, latest_period))
        
        self.stdout.write(f'Found {len(expired_but_active)} customers with expired services but marked active')
        
        for customer, period in expired_but_active:
            if not dry_run:
                customer.service_status = 'suspended'
                customer.save()
                period.status = 'expired'
                period.save()
            
            days_expired = (timezone.now().date() - period.service_end.date()).days
            self.stdout.write(
                f'{"Fixed" if not dry_run else "Would fix"}: {customer.customer_id} - {customer.display_name} '
                f'(service expired {days_expired} days ago on {period.service_end.date()})'
            )
            fixed_count += 1
        
        # 3. Show summary
        self.stdout.write(
            self.style.SUCCESS(
                f'\nSummary: {"Fixed" if not dry_run else "Would fix"} {fixed_count} customer status issues'
            )
        )
        
        if dry_run:
            self.stdout.write(
                self.style.WARNING('Run without --dry-run to actually fix these issues')
            )
