from rest_framework import permissions


# ----------------------------------------------------
# Global Role Definition
# ----------------------------------------------------
ROLES = {
    "ADMIN": "ADMIN",
    "OPERATOR": "OPERATOR",
    "VIEWER": "VIEWER",
}


# ----------------------------------------------------
# Base Role Permission (Clean Code + Robustness)
# ----------------------------------------------------
class RolePermission(permissions.BasePermission):
    """
    Base class สำหรับตรวจสอบสิทธิ์ตามฟิลด์ role (ADMIN, OPERATOR, VIEWER)
    """

    allowed_roles = []

    def has_permission(self, request, view):
        user = request.user

        if not user or not user.is_authenticated:
            return False

        # กรณีที่ไม่มี attribute ชื่อ role ก็จะไม่ทำให้เกิด AttributeError
        user_role = getattr(user, 'role', '').upper()

        return user_role in self.allowed_roles


# ----------------------------------------------------
# Specific Permission Classes
# ----------------------------------------------------
class IsAdmin(RolePermission):
    message = "คุณไม่มีสิทธิ์เข้าถึงหน้านี้ (ADMIN Required)."
    allowed_roles = [ROLES["ADMIN"]]


class IsAdminOrOperator(RolePermission):
    allowed_roles = [ROLES["ADMIN"], ROLES["OPERATOR"]]


class IsViewerOrHigher(RolePermission):
    allowed_roles = [
        ROLES["ADMIN"],
        ROLES["OPERATOR"],
        ROLES["VIEWER"],
    ]


class IsAuthenticatedAccess(permissions.IsAuthenticated):
    message = "คุณต้องเข้าสู่ระบบก่อน"
