

from django.core.management.base import BaseCommand
from apps.inventory.models import InventoryItem
from apps.business.models import Business


class Command(BaseCommand):
    help = 'Check for low stock items and send notifications'
    
    def add_arguments(self, parser):
        parser.add_argument(
            '--business-id',
            type=int,
            help='Check specific business only'
        )
    
    def handle(self, *args, **options):
        business_id = options.get('business_id')
        
        if business_id:
            businesses = Business.objects.filter(id=business_id, is_active=True)
        else:
            businesses = Business.objects.filter(is_active=True)
        
        total_low_stock = 0
        
        for business in businesses:
            low_stock_items = InventoryItem.objects.filter(
                business=business,
                quantity__lte=django_filters.F('reorder_level'),
                status='IN_STOCK'
            ).select_related('location', 'brand')
            
            count = low_stock_items.count()
            
            if count > 0:
                self.stdout.write(
                    self.style.WARNING(
                        f'Business: {business.name} - {count} low stock items'
                    )
                )
                
                for item in low_stock_items:
                    self.stdout.write(
                        f'  - {item.brand.name} {item.model} '
                        f'({item.asset_id}): {item.quantity} units '
                        f'(reorder level: {item.reorder_level})'
                    )
                
                total_low_stock += count
                
                # TODO: Send notification to business admins
                # notification_service.send_low_stock_alert(business, low_stock_items)
        
        if total_low_stock > 0:
            self.stdout.write(
                self.style.SUCCESS(
                    f'Total low stock items across all businesses: {total_low_stock}'
                )
            )
        else:
            self.stdout.write(
                self.style.SUCCESS('No low stock items found')
            )
