"""
Management command to recalculate all business ratings.
Run with: python manage.py recalculate_ratings
"""

from django.core.management.base import BaseCommand
from business.models import Business


class Command(BaseCommand):
    help = 'Recalculate total_reviews and average_rating for all businesses'

    def handle(self, *args, **options):
        businesses = Business.objects.all()
        total = businesses.count()

        self.stdout.write(f'Recalculating ratings for {total} businesses...')

        updated = 0
        for business in businesses:
            old_reviews = business.total_reviews
            old_rating = business.average_rating

            business.update_rating()

            # Refresh from database to get updated values
            business.refresh_from_db()

            if old_reviews != business.total_reviews or old_rating != business.average_rating:
                updated += 1
                self.stdout.write(
                    f'  Updated "{business.title}": '
                    f'reviews {old_reviews} -> {business.total_reviews}, '
                    f'rating {old_rating} -> {business.average_rating}'
                )

        self.stdout.write(
            self.style.SUCCESS(
                f'Done! Updated {updated} out of {total} businesses.'
            )
        )
