"""
Copy legacy AuctionListing rows into Products, so the auction section has a
single source of truth.

The old apps.auction model predates domains being sold through the shop. It is
no longer routed, so anything still held there is invisible to customers and
absent from Orders, invoices and the CRM.

Nothing is deleted. Existing products are never overwritten. Run the dry run
first:

    venv/bin/python manage.py merge_auction_listings --dry-run --settings=config.settings.production
"""
from django.core.management.base import BaseCommand
from django.utils.text import slugify

STATUS_MAP = {
    'active':      'available',
    'under_offer': 'reserved',
    'sold':        'sold',
    'draft':       'available',
}


class Command(BaseCommand):
    help = 'Copy legacy AuctionListing rows into Product records.'

    def add_arguments(self, parser):
        parser.add_argument('--dry-run', action='store_true',
                            help='Report what would happen, change nothing.')
        parser.add_argument('--include-drafts', action='store_true',
                            help='Also copy listings still in draft. They arrive inactive.')

    def handle(self, *args, **options):
        dry = options['dry_run']
        try:
            from apps.auction.models import AuctionListing
        except Exception:
            self.stdout.write('The legacy auction app is not installed. Nothing to do.')
            return

        from apps.ecommerce.models import Product

        listings = AuctionListing.objects.all()
        if not options['include_drafts']:
            listings = listings.exclude(status='draft')

        total = listings.count()
        if not total:
            self.stdout.write('No legacy listings found. Nothing to merge.')
            return

        self.stdout.write(f'{total} legacy listing(s) found.\n')
        created = skipped = 0

        for l in listings:
            slug = l.slug or slugify(l.name)
            existing = Product.objects.filter(slug=slug).first()
            if existing:
                self.stdout.write(f'  skip   {l.name}: a product already uses the slug "{slug}"')
                skipped += 1
                continue

            self.stdout.write(
                f'  {"would create" if dry else "create"} {l.name} '
                f'(slug {slug}, {l.status} -> {STATUS_MAP.get(l.status, "available")}, '
                f'price {l.asking_price or "on request"})'
            )
            if dry:
                created += 1
                continue

            Product.objects.create(
                tenant=l.tenant,
                name=l.name,
                slug=slug,
                product_type=Product.TYPE_DOMAIN,
                price=l.asking_price or 0,
                short_description=l.tagline or '',
                description=l.description or '',
                meta_description=l.meta_description or '',
                is_active=(l.status != 'draft'),
                is_featured=l.is_premium,
                show_in_shop=False,          # the auction section lists it, not the shop
                is_auction=True,
                sale_method=Product.SALE_OFFER if l.price_on_request else Product.SALE_FIXED,
                auction_status=STATUS_MAP.get(l.status, Product.AUCTION_AVAILABLE),
            )
            created += 1

        self.stdout.write('')
        verb = 'would be created' if dry else 'created'
        self.stdout.write(self.style.SUCCESS(f'{created} product(s) {verb}, {skipped} skipped.'))
        if not dry and created:
            self.stdout.write(
                'Set a reservation fee on each one in the panel. '
                'The legacy rows are untouched and can still be read if anything looks wrong.'
            )
