from django.http import JsonResponse
import os
import requests
from django.conf import settings

class SecureHeaderMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # Example: Validate API Key header
        api_key = request.headers.get('x-api-key')
        content_type = request.headers.get('x-content-type')
        auth_token = request.headers.get('x-auth-token')
        # Validate API Key
        if not api_key or api_key != os.getenv('API_KEY'):
            return JsonResponse(
                {
                    'status_code': 403,
                    'status': 'error',
                    'message': 'Invalid or missing API Key',
                    'details': 'The API key provided is either missing or invalid. Please provide a valid API key.'
                },
                status=403
            )

        # Validate Content-Type
        if not content_type or content_type != 'application/json':
            return JsonResponse(
                {
                    'status_code': 403,
                    'status': 'error',
                    'message': 'Invalid or missing Content-Type',
                    'details': 'The Content-Type header is either missing or not set. Please set it correctly.'
                },
                status=403
            )
        if not auth_token:
            return JsonResponse(
                {
                    'status_code': 403,
                    'status': 'error',
                    'message': 'Missing auth token',
                    'details': 'Auth token is missing. Please provide a valid auth token.'
                },
                status=403
            )
        api_url = settings.USER_API_URL + "validate_auth_token/"
        headers = {
            'x-api-key': settings.API_KEY,
            'x-content-type': 'application/json'
        }
        payload = {"auth_token": auth_token}
        try:
            response = requests.post(api_url, json=payload, headers=headers)

            if response.status_code != 200:
                return JsonResponse(
                    {
                        'status_code': 403,
                        'status': 'error',
                        'message': 'Invalid or expired auth token',
                        'details': 'The  token you are provided is invalid or expired. Please provide a valid auth token.'
                    },
                    status=403
                )

        except Exception as e:
            return JsonResponse(
                {
                    'status_code': 500,
                    'status': 'error',
                    'message': 'An error occurred while validating the token',
                    'details': str(e)
                },
                status=500
            )
        return self.get_response(request)
