from django.core.management.base import BaseCommand
from crm.models import Quote, Invoice


class Command(BaseCommand):
    help = 'Fix quote to invoice conversion issues'

    def handle(self, *args, **options):
        self.stdout.write('Starting quote conversion fix...')
        
        # Find quotes that are marked as converted but don't have invoices
        quotes_without_invoices = Quote.objects.filter(
            is_invoice_converted=True
        ).exclude(
            id__in=Invoice.objects.values_list('quote_id', flat=True)
        )
        
        self.stdout.write(f'Found {quotes_without_invoices.count()} quotes marked as converted but without invoices')
        
        fixed_count = 0
        for quote in quotes_without_invoices:
            try:
                # Use convert_to_invoice (single-invoice logic)
                invoice = quote.convert_to_invoice()
                if invoice:
                    self.stdout.write(
                        self.style.SUCCESS(
                            f'Successfully created invoice {invoice.invoice_number} for quote {quote.quote_number}'
                        )
                    )
                    fixed_count += 1
                else:
                    self.stdout.write(
                        self.style.ERROR(
                            f'Failed to create invoice for quote {quote.quote_number}'
                        )
                    )
            except Exception as e:
                self.stdout.write(
                    self.style.ERROR(
                        f'Error processing quote {quote.quote_number}: {str(e)}'
                    )
                )
        
        self.stdout.write(
            self.style.SUCCESS(
                f'Fixed {fixed_count} quotes successfully'
            )
        ) 