from rest_framework_simplejwt.authentication import JWTAuthentication
from rest_framework_simplejwt.exceptions import AuthenticationFailed
from rest_framework.permissions import BasePermission


class EmployeeJWTAuthentication(JWTAuthentication):
    """
    JWT Authentication for Employee users.

    Required JWT:

        type = "employee"
        user_id = employee_id
        employee_id = employee_id
        company_id = company_id
        role = employee role
    """

    def get_user(self, validated_token):

        # =====================================================
        # TOKEN TYPE CHECK
        # =====================================================

        token_type = validated_token.get("type")

        if token_type != "employee":

            raise AuthenticationFailed({
                "status": "error",
                "code": "invalid_token_type",
                "message": "Invalid employee token.",
                "data": None,
            })

        # =====================================================
        # EMPLOYEE ID
        # =====================================================

        employee_id = validated_token.get("employee_id")

        if not employee_id:

            employee_id = validated_token.get("user_id")

        if not employee_id:

            raise AuthenticationFailed({
                "status": "error",
                "code": "employee_id_missing",
                "message": "Employee ID missing from token.",
                "data": None,
            })

        # =====================================================
        # COMPANY ID
        # =====================================================

        company_id = validated_token.get("company_id")

        if not company_id:

            raise AuthenticationFailed({
                "status": "error",
                "code": "company_id_missing",
                "message": "Company ID missing from employee token.",
                "data": None,
            })

        # =====================================================
        # IMPORT MODELS
        # (additive fix: the real model is EmployeeDT, and its
        # unique identifier field is employee_code, not
        # employee_id / "Employee")
        # =====================================================

        from .models import EmployeeDT

        # =====================================================
        # GET EMPLOYEE
        # =====================================================

        try:

            employee = EmployeeDT.objects.select_related(
                "company"
            ).get(
                employee_code=employee_id
            )

            # Attach role from the linked EmployeeAccount so
            # permission classes below (which read
            # employee.role) keep working.
            account = getattr(employee, "account", None)
            employee.role = account.role if account else None

        except EmployeeDT.DoesNotExist:

            raise AuthenticationFailed({
                "status": "error",
                "code": "employee_not_found",
                "message": "Employee not found.",
                "data": None,
            })

        # =====================================================
        # EMPLOYEE ACTIVE CHECK
        # =====================================================

        if hasattr(employee, "is_active"):

            if not employee.is_active:

                raise AuthenticationFailed({
                    "status": "error",
                    "code": "employee_disabled",
                    "message": "Employee account is inactive.",
                    "data": None,
                })

        # =====================================================
        # COMPANY CHECK
        # =====================================================

        company = getattr(
            employee,
            "company",
            None
        )

        if company is None:

            raise AuthenticationFailed({
                "status": "error",
                "code": "company_not_found",
                "message": "Employee is not linked to a company.",
                "data": None,
            })

        # =====================================================
        # TOKEN COMPANY VS DATABASE COMPANY
        # =====================================================

        if str(company.company_id) != str(company_id):

            raise AuthenticationFailed({
                "status": "error",
                "code": "company_mismatch",
                "message": "Employee does not belong to this company.",
                "data": None,
            })

        # =====================================================
        # COMPANY ACTIVE CHECK
        # =====================================================

        if not company.status:

            raise AuthenticationFailed({
                "status": "error",
                "code": "company_disabled",
                "message": "Employee company is inactive.",
                "data": None,
            })

        # =====================================================
        # COMPANY VERIFICATION
        # =====================================================

        if hasattr(company, "is_verified"):

            if not company.is_verified:

                raise AuthenticationFailed({
                    "status": "error",
                    "code": "company_not_verified",
                    "message": "Company is not verified.",
                    "data": None,
                })

        # =====================================================
        # ADDITIVE: SESSION REVOCATION (AdminCenter -> Sessions)
        # Tokens issued before the actor's `revoked_before` are dead.
        # =====================================================

        from AdminCenter.common import is_token_revoked

        if is_token_revoked(validated_token, employee):

            raise AuthenticationFailed({
                "status": "error",
                "code": "token_revoked",
                "message": "This session was signed out. Please log in again.",
                "data": None,
            })

        # =====================================================
        # RETURN EMPLOYEE
        # =====================================================

        return employee


class IsEmployeeAuthenticated(BasePermission):
    """
    Allows only Employee users.
    """

    def has_permission(self, request, view):

        from .models import EmployeeDT

        return isinstance(
            request.user,
            EmployeeDT
        )


class IsEmployeeCompanyAuthenticated(BasePermission):
    """
    Employee must belong to an active company.
    """

    def has_permission(self, request, view):

        from .models import EmployeeDT

        employee = request.user

        if not isinstance(employee, EmployeeDT):
            return False

        if hasattr(employee, "is_active"):

            if not employee.is_active:
                return False

        company = getattr(
            employee,
            "company",
            None
        )

        if company is None:
            return False

        return bool(company.status)


class HasEmployeePermission(BasePermission):
    """
    Generic employee permission class.

    View must define:

        required_permission = "employee.create"

    Example:

        class EmployeeCreateView(APIView):

            authentication_classes = [
                EmployeeJWTAuthentication
            ]

            permission_classes = [
                IsEmployeeAuthenticated,
                HasEmployeePermission
            ]

            required_permission = "employee.create"
    """

    def has_permission(self, request, view):

        required_permission = getattr(
            view,
            "required_permission",
            None
        )

        if not required_permission:
            return True

        employee = request.user

        role = getattr(
            employee,
            "role",
            None
        )

        if role is None:
            return False

        # -----------------------------------------------------
        # JSON PERMISSIONS
        # -----------------------------------------------------

        permissions = getattr(
            role,
            "permissions",
            {}
        )

        if isinstance(permissions, dict):

            if permissions.get(required_permission) is True:
                return True

            if required_permission in permissions:

                return bool(
                    permissions[required_permission]
                )

        # -----------------------------------------------------
        # ROLE SUPER ACCESS
        # -----------------------------------------------------

        if getattr(
            role,
            "is_system_role",
            False
        ):

            role_code = getattr(
                role,
                "code",
                ""
            )

            if role_code in [
                "company_admin",
                "super_admin",
            ]:

                return True

        return False