from django.shortcuts import render
from rest_framework.views import APIView
from .serializers import InstitutionSerializer
from rest_framework.response import Response
from rest_framework import status
import requests
from dotenv import load_dotenv,dotenv_values
load_dotenv()
from utils.config import env
from .models import Institution
import jwt
from utils.helper import success_response, failed_response  

class UserAndInstitutionCreateView(APIView):
    def post(self, request, *args, **kwargs):
        auth_url = env['auth_url']
        user_data = request.data.get('user')
        auth_response = requests.post(auth_url, json=user_data)
        if auth_response.status_code == 200:
            auth_data = auth_response.json()
            access_token = auth_data.get("data", {}).get("token", {}).get("access")
            if access_token:
                try:
                    payload = jwt.decode(access_token, options={"verify_signature": False})
                    user_id = payload.get("user_id")
                    if not user_id:
                        return failed_response(msg="User ID cannot be decoded", code=status.HTTP_400_BAD_REQUEST)
                except jwt.DecodeError:
                    return failed_response(msg="JWT token cannot be decoded", code=status.HTTP_400_BAD_REQUEST)

            if not user_id:
                return failed_response(
                    msg="User ID not found in authentication response.",
                    code=status.HTTP_400_BAD_REQUEST
                )
            institution_data = request.data.get('institution', {})
            institution_data['user'] = user_id
            institution_serializer = InstitutionSerializer(data=institution_data)
            if institution_serializer.is_valid():
                institution = institution_serializer.save()
                return success_response({
                    "user": auth_data,
                    "institution": institution_serializer.data
                })
            return failed_response(institution_serializer.errors, code=status.HTTP_400_BAD_REQUEST)        
        return Response(auth_response.json(), status=auth_response.status_code)
    
class InstitutionListView(APIView):
    def get(self, request):
        institutions = Institution.objects.all()
        serializer = InstitutionSerializer(institutions, many=True)
        return success_response(msg=serializer.data)

class InstitutionDetailView(APIView):
    def get(self, request, pk):
        try:
            institution = Institution.objects.get(pk=pk)
            serializer = InstitutionSerializer(institution)
            return success_response(msg=serializer.data)
        except Institution.DoesNotExist:
            return failed_response(msg="Institution not found", code=status.HTTP_404_NOT_FOUND)


class InstitutionUpdateView(APIView):
    def put(self, request, pk):
        try:
            institution = Institution.objects.get(pk=pk)
        except Institution.DoesNotExist:
            return failed_response(msg="Institution not found", code=status.HTTP_404_NOT_FOUND)

        serializer = InstitutionSerializer(institution, data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
            return success_response(msg=serializer.data)
        return failed_response(msg=serializer.errors, code=status.HTTP_400_BAD_REQUEST)


class InstitutionDeleteView(APIView):
    def delete(self, request, pk):
        try:
            institution = Institution.objects.get(pk=pk)
            institution.delete()
            return Response(status=status.HTTP_204_NO_CONTENT)
        except Institution.DoesNotExist:
            return failed_response(msg="Institution not found", code=status.HTTP_404_NOT_FOUND)