"""Public/private and online/offline visibility rules for profiles."""
from django.http import Http404
from django.shortcuts import get_object_or_404


def visible_companies(*, online_only=False):
    from companies.models import Company

    queryset = Company.objects.filter(is_active=True, is_public=True)
    if online_only:
        queryset = queryset.filter(is_online=True)
    return queryset


def visible_seekers(*, online_only=False):
    from seekers.models import SeekerProfile

    queryset = SeekerProfile.objects.filter(is_public=True)
    if online_only:
        queryset = queryset.filter(is_online=True).exclude(visibility='recruiters')
    return queryset


def user_can_view_seeker_profile(user, profile):
    owner = user.is_authenticated and profile.user_id == user.id
    admin = user.is_authenticated and getattr(user, 'is_platform_admin', False)
    if owner or admin:
        return True
    if not profile.is_public:
        return False
    if getattr(profile, 'visibility', 'public') == 'recruiters':
        return bool(user.is_authenticated and getattr(user, 'is_company', False))
    return True


def user_can_view_company(user, company):
    if not company.is_active:
        if user.is_authenticated and (
            company.owner_id == user.id or getattr(user, 'is_platform_admin', False)
        ):
            return True
        return False
    if company.is_public:
        return True
    if user.is_authenticated and company.owner_id == user.id:
        return True
    if user.is_authenticated and getattr(user, 'is_platform_admin', False):
        return True
    return False


def get_visible_seeker_or_404(request, slug):
    from seekers.models import SeekerProfile

    profile = get_object_or_404(SeekerProfile, slug=slug)
    if not user_can_view_seeker_profile(request.user, profile):
        raise Http404
    return profile


def get_visible_company_or_404(request, slug):
    from companies.models import Company

    company = get_object_or_404(Company, slug=slug, is_active=True)
    if not user_can_view_company(request.user, company):
        raise Http404
    return company
