from django.conf import settings
from django.shortcuts import redirect

from oauth.hep_client import HepClient
from oauth.oauth_client import oauth
from oauth.models import OAuth2Token
from oauth.user_signup_login_handler import handle_user_and_verify_products, EMAIL_NOT_VERIFIED
from django.contrib.auth import login as dj_login


def login(request):
    hep_oauth_client = oauth.create_client('hep')
    redirect_uri = settings.OAUTH_LOCAL_REDIRECT_URI
    return hep_oauth_client.authorize_redirect(request, redirect_uri)


def authorize(request):
    hep_client = HepClient()
    token = oauth.hep.authorize_access_token(request)
    user_data = hep_client.user_details(token=token)

    user, status_msg = handle_user_and_verify_products(user_data)
    user.sync_with_hep_data(user_data)

    if user and status_msg != EMAIL_NOT_VERIFIED:
        dj_login(request, user)

    OAuth2Token.objects.update_or_create_token(token, user)

    if status_msg:
        return redirect(f'/login-success?state={status_msg}')
        # return status_msg
        # return cls.return_login_message(status_msg)
    return redirect(f'/login-success?state={status_msg}')
