from django.core.cache import cache
from django.core.management.base import BaseCommand

from apps.core.analytics import PageView
from apps.parks.models import Park
from apps.rides.models import Ride


class Command(BaseCommand):
    help = "Updates trending parks and rides cache based on views in the last 7 days"

    def handle(self, *args, **kwargs):
        """
        Updates the trending parks and rides in the cache.

        This command is designed to be run once daily via cron to keep the trending
        items up to date. It looks at page views from the last 7 days and caches
        the top 10 most viewed parks and rides.

        The cached data is used by the home page to display trending items without
        having to query the database on every request.
        """
        # Get top 10 trending parks and rides from the last 7 days (168 hours)
        trending_parks = PageView.get_trending_items(Park, hours=168, limit=10)
        trending_rides = PageView.get_trending_items(Ride, hours=168, limit=10)

        # Cache the results for 24 hours (daily refresh)
        cache.set("trending_parks", trending_parks, 86400)  # 86400 seconds = 24 hours
        cache.set("trending_rides", trending_rides, 86400)

        self.stdout.write(
            self.style.SUCCESS(
                "Successfully updated trending parks and rides. "
                "Cached 10 items each for parks and rides based on views "
                "in the last 7 days."
            )
        )
