from __future__ import annotations

from django.core.management.base import BaseCommand
from django.utils import timezone

from recycle_core.models import ScrapListing, ScrapBid, ScrapAward, PickupOrder


class Command(BaseCommand):
    help = "Auto-close expired scrap listings and award to highest bids meeting reserve"

    def handle(self, *args, **options):
        now = timezone.now()
        closed = 0
        awarded = 0
        # Close open listings past ends_at
        for listing in ScrapListing.objects.filter(status=ScrapListing.STATUS_OPEN, ends_at__isnull=False, ends_at__lt=now):
            listing.status = ScrapListing.STATUS_CLOSED
            listing.save(update_fields=["status"])
            closed += 1

        # Award closed, unawarded listings
        for listing in ScrapListing.objects.filter(status=ScrapListing.STATUS_CLOSED):
            if hasattr(listing, "award") and listing.award_id:
                continue
            top_bid = (
                ScrapBid.objects.filter(listing=listing, status=ScrapBid.STATUS_ACTIVE)
                .order_by("-price_total")
                .first()
            )
            if not top_bid:
                continue
            if listing.reserve_price and top_bid.price_total < listing.reserve_price:
                continue
            # Reject others and accept top
            ScrapBid.objects.filter(listing=listing, status=ScrapBid.STATUS_ACTIVE).exclude(id=top_bid.id).update(status=ScrapBid.STATUS_REJECTED)
            top_bid.status = ScrapBid.STATUS_ACCEPTED
            top_bid.save(update_fields=["status"])
            listing.status = ScrapListing.STATUS_AWARDED
            listing.save(update_fields=["status"]) 
            pickup = PickupOrder.objects.create(
                organization=listing.organization,
                customer=listing.customer,
                site=listing.site,
                status=PickupOrder.STATUS_SCHEDULED,
                notes=f"Auto-awarded to org {top_bid.bidder_org_id} for listing {listing.id}",
            )
            ScrapAward.objects.create(listing=listing, winning_bid=top_bid, pickup=pickup)
            awarded += 1

        self.stdout.write(self.style.SUCCESS(f"Closed: {closed}, Awarded: {awarded}"))

