from rest_framework.views import APIView
from rest_framework.response import Response
from .models import Plan, BillingCycle
from .serializers import PlanSerializer, BillingCycleSerializer
from rest_framework.pagination import PageNumberPagination
# Serializer to convert models to JSON
from rest_framework import serializers

class BillingCycleSerializer(serializers.ModelSerializer):
    class Meta:
        model = BillingCycle
        fields = ['type', 'price']

class PlanSerializer(serializers.ModelSerializer):
    billing_cycles = BillingCycleSerializer(many=True)

    class Meta:
        model = Plan
        fields = ['plan_name', 'speed', 'base_price', 'data', 'wifi_router', 'tv_channels', 
                  'setup_fee', 'otts', 'hotstar', 'prime', 'billing_cycles']


# API View to get pricing plansclass PlanPagination(PageNumberPagination):

class PlanPagination(PageNumberPagination):
    page_size = 1000
    page_size_query_param = 'page_size'
    max_page_size = 1000

from rest_framework.views import APIView
from rest_framework.response import Response
from .models import Plan
from .serializers import PlanSerializer

class PricingPlanView(APIView):
    def get(self, request):
        plans = Plan.objects.prefetch_related('billing_cycles').all()
        serializer = PlanSerializer(plans, many=True)
        data = serializer.data

        # Extract and sort unique speed values
        speeds_set = set()
        for plan in data:
            speed_str = plan['speed'].lower().replace('mbps', '').strip()
            if speed_str.isdigit():
                speeds_set.add(int(speed_str))
        speeds = sorted(speeds_set)
        speeds = [f"{s} Mbps" for s in speeds]

        # Extract and sort OTT counts
        otts = sorted(set(plan['otts'] for plan in data))
        ottOptions = [f"{o}" for o in otts]

        # Extract and sort TV channel counts
        tv_channels = sorted(set(plan['tv_channels'] for plan in data))
        tvChannel = [f"{c}" for c in tv_channels]

        # Extract and sort billing cycle types in desired order
        desired_order = ['Monthly', 'Quarterly', 'Half Yearly', 'Yearly']
        cycle_set = set()
        for plan in data:
            for cycle in plan.get('billing_cycles', []):
                cycle_set.add(cycle['type'])
        billedCycle = [cycle for cycle in desired_order if cycle in cycle_set]

        return Response({
            "count": len(data),          
            "speeds": speeds,
            "ottOptions": ottOptions,
            "tvChannel": tvChannel,
            "billedCycle": billedCycle,
            "results": data,
        })
