from lcrequests.umbrella import User as UmbrellaUser
from typing import Optional, TYPE_CHECKING

from django.contrib.auth import get_user_model

if TYPE_CHECKING:
    from sandbox.latchstring.models import User as UserType
    from .tokens import AccessToken

User = get_user_model()


def lookup_user_record(token: 'AccessToken') -> Optional['UserType']:
    """
    Lookup user record from token claims
    """
    lookup_creds = token.get_claimed_creds()
    if cid := lookup_creds.get('user_cid'):
        return User.objects.filter(cid=cid).first()
    elif email := lookup_creds.get('email'):
        return User.objects.filter(email=email).first()

    return None


def confirm_umbrella_user(user: UmbrellaUser) -> Optional['UserType']:
    """
    Ensure that Umbrella User exists in the console database.
    """
    if User.objects.filter(cid=user.cid).exists():
        return

    return User.objects.create(
        username=user.username,
        first_name=user.first_name,
        last_name=user.last_name,
        email=user.email,
        cid=user.cid,
    )
