# ============================================================
# Admin / HR permissions - FULLY DYNAMIC, MODULE-AWARE
# ------------------------------------------------------------
# Two actor types can use the Admin/HR APIs:
#
#   1. Company Admin  -> authenticated via
#      Company.company_authentication.CompanyJWTAuthentication
#      request.user is a Company.models.company_details instance.
#      Always allowed.
#
#   2. Employee with a role -> authenticated via
#      Employee.employee_authentication.EmployeeJWTAuthentication
#      request.user is an Employee.models.EmployeeDT instance,
#      with `.role` attached (an EmployeeRole instance, or None).
#
# NO role_code is hardcoded anywhere. Every company creates its own
# roles and ticks the checkboxes on EmployeeRole. Each view belongs
# to a "module" (employees, attendance, payroll, leave, ...) and
# the HTTP method decides the action:
#
#   GET/HEAD/OPTIONS -> can_view_<module>
#   POST             -> can_create_<module>
#   PUT/PATCH        -> can_edit_<module>
#   DELETE           -> can_delete_<module>
#   can_manage_<module> -> everything for that module
#
# An employee with no role, an inactive role, or a role belonging
# to a different company is rejected (403).
#
# NOTE: request.user objects here are plain Django models, not
# Django's auth.User, so they do NOT have `.is_authenticated`.
# We rely on isinstance() checks only.
# ============================================================

from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from rest_framework.permissions import BasePermission


# Role codes (on EmployeeRole.role_code) that were treated as "HR" by
# the old, hardcoded check. KEPT for backward compatibility only:
# access is now decided by the EmployeeRole checkboxes (see
# role_allows / IsAdminOrHR below), NOT by these codes.
HR_ROLE_CODES = {"hr", "hr_manager", "human_resource", "human_resources"}


# HTTP method -> generic action name
METHOD_TO_ACTION = {
    "GET": "view",
    "HEAD": "view",
    "OPTIONS": "view",
    "POST": "create",
    "PUT": "edit",
    "PATCH": "edit",
    "DELETE": "delete",
}

# Role flags that mean "more than read-only" (used only to label an
# employee as "hr" in resolve_actor_role - never for enforcement).
WRITE_FLAG_PREFIXES = (
    "can_create_",
    "can_edit_",
    "can_delete_",
    "can_manage_",
    "can_approve_",
)


def role_allows(role, module, action):
    """
    Dynamic check against the EmployeeRole checkboxes.

      module : "employees", "attendance", "payroll", "leave",
               "expense", "invoice", "bank", "reports", "devices",
               "company", "roles" ...
      action : "view", "create", "edit", "delete", "approve"

    Rules:
      - can_manage_<module>   -> always allowed
      - can_<action>_<module> -> allowed if that checkbox exists
        and is ticked. If the role has no such checkbox (e.g.
        there is no can_edit_leave), only can_manage_<module>
        can allow it.
    """

    if role is None:
        return False

    if getattr(role, f"can_manage_{module}", False):
        return True

    return bool(getattr(role, f"can_{action}_{module}", False))


def resolve_company_for_user(user):
    """
    Given request.user (either a company_details instance or an
    EmployeeDT instance), return the company_details this user
    belongs to / represents. Returns None for anything else.
    """

    from Company.models import company_details
    from .models import EmployeeDT

    if isinstance(user, company_details):
        return user

    if isinstance(user, EmployeeDT):
        return getattr(user, "company", None)

    return None


def _role_is_usable(user):
    """
    Returns the user's EmployeeRole if it can be used for
    permission checks, else None.

    A role is usable only if:
      - it exists,
      - it is active,
      - it belongs to the same company as the user.
    """

    role = getattr(user, "role", None)

    if role is None:
        return None

    if not getattr(role, "is_active", True):
        return None

    user_company_id = getattr(user, "company_id", None)
    role_company_id = getattr(role, "company_id", None)

    if (
        user_company_id is not None
        and role_company_id is not None
        and user_company_id != role_company_id
    ):
        return None

    return role


def user_can(user, module, action):
    """
    True if `user` (company_details or EmployeeDT) may perform
    `action` on `module`. Company admin -> always True.
    Handy inside views for extra checks.
    """

    from Company.models import company_details
    from .models import EmployeeDT

    if isinstance(user, company_details):
        return True

    if isinstance(user, EmployeeDT):
        return role_allows(_role_is_usable(user), module, action)

    return False


def actor_label(user):
    """
    Audit label for created_by / updated_by columns, e.g.
    "admin:C8829CD0" or "employee:7518A82C".
    """

    from Company.models import company_details
    from .models import EmployeeDT

    if isinstance(user, company_details):
        return f"admin:{getattr(user, 'company_id', user.pk)}"

    if isinstance(user, EmployeeDT):
        return f"employee:{getattr(user, 'employee_code', user.pk)}"

    return None


def resolve_actor_role(user):
    """
    Returns "admin", "hr", "employee" or None, for use in
    responses / logging. Does not enforce anything by itself.

    "hr" simply means: an employee whose role has at least one
    write-type checkbox ticked (create/edit/delete/manage/approve).
    Fully dynamic - no role_code is hardcoded.
    """

    from Company.models import company_details
    from .models import EmployeeDT

    if isinstance(user, company_details):
        return "admin"

    if isinstance(user, EmployeeDT):

        role = _role_is_usable(user)

        if role is not None:
            for field in role._meta.fields:
                if field.name.startswith(WRITE_FLAG_PREFIXES) and getattr(
                    role, field.name, False
                ):
                    return "hr"

        return "employee"

    return None


class AdminOrEmployeeJWTAuthentication(BaseAuthentication):
    """
    Tries CompanyJWTAuthentication first, then falls back to
    EmployeeJWTAuthentication.

    WHY THIS EXISTS (not just authentication_classes = [Company,
    Employee]):
    DRF authenticators are tried in order, BUT as soon as one of
    them raises AuthenticationFailed (rather than returning None),
    DRF stops and surfaces that error - it does NOT fall through
    to the next authenticator in the list. Both
    CompanyJWTAuthentication.get_user() and
    EmployeeJWTAuthentication.get_user() raise AuthenticationFailed
    for a token whose `type` claim doesn't match their own (e.g. a
    valid "employee" token hitting CompanyJWTAuthentication), which
    would incorrectly reject a valid employee token before
    EmployeeJWTAuthentication is ever tried.

    This wrapper explicitly swallows a "wrong token type for this
    authenticator" failure from Company auth and retries with
    Employee auth, without modifying either of the existing,
    working authentication classes.
    """

    def authenticate(self, request):

        from Company.company_authentication import CompanyJWTAuthentication
        from .employee_authentication import EmployeeJWTAuthentication

        try:
            result = CompanyJWTAuthentication().authenticate(request)
        except AuthenticationFailed:
            result = None

        if result is not None:
            return result

        # No Authorization header at all -> let this return None too,
        # so DRF correctly reports 401 "not authenticated" rather
        # than masking it as a 403 from IsAdminOrHR.
        if not request.META.get("HTTP_AUTHORIZATION"):
            return None

        return EmployeeJWTAuthentication().authenticate(request)

    def authenticate_header(self, request):
        return "Bearer"


class IsAdminOrHR(BasePermission):
    """
    Fully dynamic, module-aware permission. The class name is kept
    so existing views keep working.

    Each view says which module it belongs to:

        class PayrollListView(AdminOrHRAPIView):
            permission_module = "payroll"

    (no attribute -> "employees"). The HTTP method decides the
    action (GET=view, POST=create, PUT/PATCH=edit, DELETE=delete).

    Optional per-view overrides:
        permission_action = "edit"          # force one action
        permission_write_action = "edit"    # any write -> this action
        permission_action_map = {"approve": "approve"}
                                            # ViewSet action -> action

    Company Admin -> always allowed. Employee -> allowed only if
    their (active, same-company) role has the matching checkbox
    (or can_manage_<module>). Otherwise 403.
    """

    message = "You do not have permission to perform this action."

    def has_permission(self, request, view):

        actor = resolve_actor_role(request.user)

        # Company admin: always allowed
        if actor == "admin":
            return True

        # Not an employee at all (or unknown user type)
        if actor is None:
            return False

        role = _role_is_usable(request.user)

        if role is None:
            return False

        module = getattr(view, "permission_module", "employees")

        # A permission subclass can pin the action (used by function
        # views whose HTTP method does not match what they do, e.g.
        # "delete via POST").
        action = getattr(self, "forced_action", None)

        view_action = getattr(view, "action", None)
        action_map = getattr(view, "permission_action_map", None) or {}

        if action is None and view_action and view_action in action_map:
            action = action_map[view_action]

        if action is None:
            action = getattr(view, "permission_action", None)

        if action is None:
            action = METHOD_TO_ACTION.get(request.method)

            # e.g. holidays: module "company" has no create/delete
            # checkbox, so every write counts as "edit".
            write_action = getattr(view, "permission_write_action", None)

            if write_action and action not in (None, "view"):
                action = write_action

        if action is None:
            return False

        return role_allows(role, module, action)


class IsAdminOrHREdit(IsAdminOrHR):
    """Same as IsAdminOrHR but always checks the EDIT checkbox."""

    forced_action = "edit"


class IsAdminOrHRDelete(IsAdminOrHR):
    """Same as IsAdminOrHR but always checks the DELETE checkbox."""

    forced_action = "delete"


# ============================================================
# Per-employee record access (payslip, calendar, day detail ...)
# ============================================================

def get_employee_for_actor(user, employee_code, module, action="view"):
    """
    Returns the EmployeeDT `employee_code` if `user` may access it,
    else raises Http404 / PermissionDenied.

    Rules (multi-company safe):
      - The target must belong to the SAME company as the caller.
        Another company's employee -> 404 (never reveals that the
        code exists).
      - An employee may always access their own record.
      - Company Admin may access anyone in their company.
      - Any other employee needs the matching role checkbox
        (`can_<action>_<module>` or `can_manage_<module>`).

    NOTE: never use hasattr(user, "company_id") for this - both
    company_details and EmployeeDT have that attribute.
    """

    from django.http import Http404
    from rest_framework.exceptions import PermissionDenied
    from Company.models import company_details
    from .models import EmployeeDT

    company = resolve_company_for_user(user)

    if company is None:
        raise PermissionDenied("Unable to resolve your company. Access denied.")

    target = (
        EmployeeDT.objects.filter(employee_code=employee_code)
        .select_related("company")
        .first()
    )

    if target is None or target.company_id != company.pk:
        raise Http404("Employee not found.")

    if isinstance(user, company_details):
        return target

    if isinstance(user, EmployeeDT):

        if user.pk == target.pk:
            return target

        if role_allows(_role_is_usable(user), module, action):
            return target

    raise PermissionDenied("You do not have permission to access this record.")

