"""
Utility functions mainly to check user permissions and access to views
"""

from django.contrib.auth.models import User
from django.db.models import QuerySet

from allianceauth.authentication.models import CharacterOwnership
from allianceauth.eveonline.models import EveAllianceInfo, EveCorporationInfo
from allianceauth.services.hooks import get_extension_logger

from corphandouts.models import DoctrineReport

logger = get_extension_logger(__name__)


def user_has_citadel_fitting_access(user: User):
    """Check if a user can access the citadel fittings part of the application"""
    return any(
        [
            user.has_perm("corphandouts.corporation_view"),
            user.has_perm("corphandouts.alliance_view"),
            user.has_perm("corphandouts.manager"),
        ]
    )


def get_user_alliances(user: User) -> QuerySet[EveAllianceInfo]:
    """Return all alliances the user has a character in"""
    alliances_ids = (
        CharacterOwnership.objects.filter(user=user)
        .values_list("character__alliance_id", flat=True)
        .distinct()
    )
    alliances = EveAllianceInfo.objects.filter(alliance_id__in=alliances_ids)

    return alliances


def get_user_corporations(user: User) -> QuerySet[EveCorporationInfo]:
    """Return all corporations the user has a character in"""
    corporation_ids = (
        CharacterOwnership.objects.filter(user=user)
        .values_list("character__corporation_id", flat=True)
        .distinct()
    )
    corporations = EveCorporationInfo.objects.filter(corporation_id__in=corporation_ids)

    return corporations


def user_can_view_citadel_doctrine(user: User, doctrine: DoctrineReport) -> bool:
    """Checks if the user has the appropriate permission to check a doctrine"""
    logger.debug(
        "Checking if user id %d can access doctrine id %d", user.id, doctrine.id
    )
    can_view_doctrine = False
    if user.has_perm("corphandouts.manager"):
        logger.debug("User id %d is manager", user.id)
        can_view_doctrine = True
    elif user.has_perm("corphandouts.alliance_view"):
        user_alliances = get_user_alliances(user)
        logger.debug(user_alliances)
        doctrine_alliance = doctrine.corporation.corporation.alliance
        can_view_doctrine = doctrine_alliance in user_alliances
    elif user.has_perm("corphandouts.corporation_view"):
        user_corporations = get_user_corporations(user)
        logger.debug(user_corporations)
        doctrine_corporation = doctrine.corporation.corporation
        can_view_doctrine = doctrine_corporation in user_corporations

    return can_view_doctrine


def user_can_access_view(user: User, doctrine: DoctrineReport) -> bool:
    """
    Checks if the user can access the view based on:
        - corphandouts.basic_access if handout doctrine
        - corporation affiliation if citadel doctrine
    """
    can_access_view = False
    logger.debug(
        "Check if user id %d can access view of doctrine id %d", user.id, doctrine.id
    )
    if doctrine.corporation_hangar_division != 0:
        can_access_view = user.has_perm("corphandouts.basic_access")
    else:
        can_access_view = user_can_view_citadel_doctrine(user, doctrine)

    return can_access_view
