"""Authorization helpers for shops."""

from .models import Shop


def _main_corp_id(user):
    main = getattr(getattr(user, "profile", None), "main_character", None)
    return main.corporation_id if main else None


def can_manage(user, shop) -> bool:
    """Whether `user` may manage (edit/delete/preview) `shop`."""
    if not user.is_authenticated:
        return False
    if user.is_superuser:
        return True
    if shop.shop_type == Shop.ShopType.PERSONAL:
        return shop.created_by_id == user.id
    # corporation shop
    if not user.has_perm("shop.manage_corporation_shops"):
        return False
    if shop.corporation_id is None:
        return False
    return shop.corporation.corporation_id == _main_corp_id(user)


def personal_shops_for(user):
    return Shop.objects.filter(
        shop_type=Shop.ShopType.PERSONAL, created_by=user
    ).order_by("name")


def corp_shops_for(user):
    """Corp shops the user may see in the back-office."""
    if user.is_superuser:
        return Shop.objects.filter(
            shop_type=Shop.ShopType.CORPORATION
        ).order_by("name")
    if not user.has_perm("shop.manage_corporation_shops"):
        return Shop.objects.none()
    corp_id = _main_corp_id(user)
    if corp_id is None:
        return Shop.objects.none()
    return Shop.objects.filter(
        shop_type=Shop.ShopType.CORPORATION,
        corporation__corporation_id=corp_id,
    ).order_by("name")
