from django.conf import settings
from apps.accounts.permissions import (
    ROLE_ACCOUNTS, ROLE_EMPLOYEE, ROLE_HR_ADMIN, ROLE_IT, ROLE_MANAGER, ROLE_PAYROLL_OFFICER, ROLE_SUPER_ADMIN,
    accessible_company_ids, default_company_id, has_role,
)
from .models import Company


def company_branding(request):
    company = None
    user = getattr(request, "user", None)
    authenticated = bool(user and getattr(user, "is_authenticated", False))
    if authenticated:
        company_id = default_company_id(user)
        if company_id:
            company = Company.objects.filter(pk=company_id).first()

    is_super = bool(authenticated and (getattr(user, "is_superuser", False) or has_role(user, ROLE_SUPER_ADMIN)))
    is_hr = bool(authenticated and has_role(user, ROLE_HR_ADMIN))
    is_payroll = bool(authenticated and has_role(user, ROLE_PAYROLL_OFFICER))
    is_accounts = bool(authenticated and has_role(user, ROLE_ACCOUNTS))
    is_manager = bool(authenticated and has_role(user, ROLE_MANAGER))
    is_it = bool(authenticated and has_role(user, ROLE_IT))
    is_employee = bool(authenticated and has_role(user, ROLE_EMPLOYEE))
    group_names = list(user.groups.values_list("name", flat=True)) if authenticated and not getattr(user, "is_superuser", False) else []
    role_label = "Super Admin" if getattr(user, "is_superuser", False) else (", ".join(group_names) if group_names else "Authorized User")
    employee_profile = getattr(user, "employee_profile", None) if authenticated else None
    company_scope = set(accessible_company_ids(user)) if authenticated else set()
    can_submit_employee_request = bool(
        employee_profile
        and getattr(employee_profile, "company_id", None)
        and employee_profile.company_id in company_scope
    )

    return {
        "brand_company": company,
        "project_reference": settings.PROJECT_REFERENCE,
        "can_administer_hr": is_super or is_hr,
        "can_manage_attendance": is_super or is_hr,
        "can_manage_payroll": is_super or is_hr or is_payroll,
        "can_view_reports": is_super or is_hr or is_payroll or is_accounts,
        "can_manage_payroll_inputs": is_super or is_hr or is_payroll,
        "can_manage_loans": is_super or is_hr or is_accounts,
        "can_manage_exit": is_super or is_hr,
        "can_view_team": is_super or is_hr or is_manager,
        "can_view_system_ops": bool(getattr(user, "is_superuser", False)),
        "role_label": role_label,
        "is_manager_role": is_manager,
        "is_employee_role": is_employee,
        "is_it_role": is_it,
        "can_submit_employee_request": can_submit_employee_request,
    }
