from django.core.management.base import BaseCommand
from hotel.models import HotelBooking
from hotel.pms_integration import PMSService

class Command(BaseCommand):
    help = 'Sync existing confirmed HotelBookings to Aatithya PMS'

    def handle(self, *args, **options):
        # Fetch all confirmed bookings
        bookings = HotelBooking.objects.filter(status='confirmed').order_by('id')
        self.stdout.write(self.style.NOTICE(f"Found {bookings.count()} confirmed bookings to sync."))
        
        success_count = 0
        fail_count = 0
        
        for booking in bookings:
            guest_display = booking.guest_name or booking.user.username
            self.stdout.write(f"Syncing booking {booking.id} (Guest: {guest_display})...")
            try:
                success = PMSService.send_booking(booking)
                if success:
                    self.stdout.write(self.style.SUCCESS(f"Successfully synced booking {booking.id}"))
                    success_count += 1
                else:
                    self.stdout.write(self.style.ERROR(f"Failed to sync booking {booking.id}"))
                    fail_count += 1
            except Exception as e:
                self.stdout.write(self.style.ERROR(f"Exception syncing booking {booking.id}: {str(e)}"))
                fail_count += 1
                
        self.stdout.write(self.style.NOTICE(
            f"Synchronization completed. Success: {success_count}, Failed: {fail_count}"
        ))
