from django.http import JsonResponse
import os
from user_app.models import UserLogins

class SecureHeaderMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):

        api_key = request.headers.get('x-api-key')
        content_type = request.headers.get('x-content-type')
        auth_token = request.headers.get('x-auth-token')
        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
            )

        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
            )
        # Exclude login API from token checking

        if request.path.startswith('/user_service/login/'):  # Adjust this to your actual login endpoint
            return self.get_response(request)
        if request.path.startswith('/user_service/validate_auth_token/'):  # Adjust this to your actual login endpoint
            return self.get_response(request)
        if not auth_token:
            return JsonResponse(
                {
                    'status_code': 403,
                    'status': 'error',
                    'message': 'Missing Authentication Tokenssss',
                    'details': 'Please provide a valid authentication token in the Authorization header.'
                },
                status=403
            )

        try:
            # Get the user associated with the token (assuming the token is unique to the user)
            user_login = UserLogins.objects.filter(AuthToken=auth_token, IsActive=1).first()

            if not user_login:
                return JsonResponse(
                    {
                        'status_code': 403,
                        'status': 'error',
                        'message': 'Invalid or expired authentication token',
                        'details': 'The provided authentication token is either invalid or expired.'
                    },
                    status=403
                )

            # Optional: Check if the token matches the user ID
            # user = user_login.user  # Adjust this based on your UserLogins model
            # if user.id != request.user.id:
            #     return JsonResponse(
            #         {
            #             'status_code': 403,
            #             'status': 'error',
            #             'message': 'Unauthorized token',
            #             'details': 'The provided authentication token does not match the logged-in user.'
            #         },
            #         status=403
            #     )

        except UserLogins.DoesNotExist:
            return JsonResponse(
                {
                    'status_code': 403,
                    'status': 'error',
                    'message': 'Authentication failed',
                    'details': 'Authentication token is missing or invalid.'
                },
                status=403
            )

        return self.get_response(request)
