from allauth.account.adapter import DefaultAccountAdapter
from allauth.utils import build_absolute_uri
from django.conf import settings

class CustomAccountAdapter(DefaultAccountAdapter):

    def get_email_confirmation_url(self, request, emailconfirmation):
        origin = request.META.get('HTTP_ORIGIN', None)
        referer_host = request.META.get('HTTP_REFERER', None)
        # if referer_host:
        #     base_url = referer_host  # Use Referer as the base URL
        if origin:
            base_url = origin
        else:
            base_url = f"{request.scheme}://{request.get_host()}"
        if base_url.endswith('/'):
            base_url = base_url[:-1]
        ret = f"{base_url}/users/verifyemail/?key={emailconfirmation.key}"
        return ret
    
    # """
    # Custom adapter to handle password reset URL customization.
    # """
    # def get_password_reset_url(self, request):
    #     """
    #     Customizes the URL used in the password reset email.
    #     """
    #     # First, try to use the Origin header if it exists
    #     origin = request.META.get('HTTP_ORIGIN', None)

    #     if origin:
    #         # If Origin header is found, use it as the base URL
    #         base_url = origin
    #         print(f"Using Origin header as base URL: {base_url}")
    #     else:
    #         # Fallback to the request's host (default behavior)
    #         base_url = f"{request.scheme}://{request.get_host()}"
    #         print(f"Using Host as base URL: {base_url}")

    #     # Remove trailing slash if it exists
    #     if base_url.endswith('/'):
    #         base_url = base_url[:-1]
    #         print(f"Trailing slash removed from base URL: {base_url}")

    #     # Use the custom URL pattern for password reset
    #     reset_url = f"{base_url}/reset-password/?key={request.user.password_reset_token}"
    #     print(f"Final password reset URL: {reset_url}")

    #     return reset_url
    def send_mail(self, template_prefix, email, context):
        """
        Override to customize the password reset URL in the context.
        """
        request = context.get("request")
        if request:
            # origin = request.META.get('HTTP_ORIGIN', None)
            # if origin:
            #     base_url = origin
            # else:
            #     base_url = f"{request.scheme}://{request.get_host()}"

            base_url = settings.FRONTEND_URL
            if base_url.endswith('/'):
                base_url = base_url[:-1]

            # Update the password reset URL in the context
            # print(context)
            if "password_reset_url" in context:
                # print(context)
                context["password_reset_url"] = f"{base_url}/users/reset-password/?token={context['token']}&uid={context['uid']}"
        super().send_mail(template_prefix, email, context)