from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAdminUser
from apps.business.schemes.models import OpportunityBundle, OpportunityBundleLevel, OpportunityBundleDistribution
from apps.business.power_stream.models import PowerStreamConfig
from apps.business.schemes.serializers import OpportunityBundleLevelSerializer, OpportunityBundleDistributionSerializer
from rest_framework import status
from apps.core.utils import error_response

class SchemeLevelsConfigAPIView(APIView):
    permission_classes = [IsAdminUser]
    def get(self, request, id):
        try:
            bundle = OpportunityBundle.objects.get(id=id)
        except OpportunityBundle.DoesNotExist:
            return error_response("opportunity_bundle not found", code="SCHEME_NOT_FOUND", status_code=status.HTTP_404_NOT_FOUND)
        levels = OpportunityBundleLevel.objects.filter(opportunity_bundle=bundle).order_by('display_order')
        data = OpportunityBundleLevelSerializer(levels, many=True).data
        return Response({"success": True, "data": data})

class SchemeDistributionConfigAPIView(APIView):
    permission_classes = [IsAdminUser]
    def get(self, request, id):
        try:
            bundle = OpportunityBundle.objects.get(id=id)
        except OpportunityBundle.DoesNotExist:
            return error_response("opportunity_bundle not found", code="SCHEME_NOT_FOUND", status_code=status.HTTP_404_NOT_FOUND)
        distributions = OpportunityBundleDistribution.objects.filter(opportunity_bundle=bundle)
        data = OpportunityBundleDistributionSerializer(distributions, many=True).data
        return Response({"success": True, "data": data})

class SchemePowerStreamConfigAPIView(APIView):
    permission_classes = [IsAdminUser]
    def get(self, request, id):
        try:
            bundle = OpportunityBundle.objects.get(id=id)
        except OpportunityBundle.DoesNotExist:
            return error_response("opportunity_bundle not found", code="SCHEME_NOT_FOUND", status_code=status.HTTP_404_NOT_FOUND)
        configs = PowerStreamConfig.objects.filter(opportunity_bundle=bundle).order_by('level')
        data = [
            {"level": c.level, "amount": str(c.amount)} for c in configs
        ]
        return Response({"success": True, "data": data})
