from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
import requests
from app1.serializers import *
from app1.fun_call import *
# Create your views here.

class Lead_Search(APIView):
     def post(self, request):
        try:
            pageSize = request.data.get('num_lead',10)
            if pageSize > 40:
                return Response({'status': False, 'message': f"You can't search more then 10 contacts, because you don't have enough credits"})
            jobTitle = request.data.get('jobTitle',[])
            location = request.data.get('location',[])
            industry = request.data.get('industry',[])
            payload = {
                "jobTitle": { "included": jobTitle },
                "location": { "included": location },
                "industry": { "included": industry }
            }
            url = f"https://api.getprospect.com/public/v1/insights/contacts?pageSize={pageSize}"
            headers = {
                "accept": "application/json",
                "content-type": "application/json",
                # "apiKey":"e2af616d-5b66-44d4-9597-601e7050f9bf"
                "apiKey": "d26c9532-b2d7-43a2-bd16-b5b0f85d74d2"
            }
            # Make the API call
            response = requests.post(url, json=payload, headers=headers,)
            

            # return Response({'status': True, 'message': 'lead data', 'file':serializer.data})
            if response.status_code == 200:
                row_data = response.json()

                leads_data = transform_data(row_data)  
                # Assuming `leads_data` contains the data retrieved from the API
                serializer = ReportDataSerializer(data={}, context={'leads': leads_data,'request': request})
                if serializer.is_valid():
                    serializer.save()
                    data = serializer.data
                    return Response({'status': True, "message": data.get('lead_file','Data not found')})
                return Response({'status': False, 'message': 'Data not found'})
            elif response.status_code == 400:
                errors = response.json()
                return Response({'status': False, 'message': errors.get('errors','Data Not Found!')})
            else:
                return Response({'status': False, 'message': 'Failed to fetch data from the API'})
        except Exception as e:
            return Response({'status':False,
                             'message':"Somthing went wrong!",'error':str(e)})
        
          