from django.utils import timezone

from rest_framework import status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from Employee.employee_crud_permissions import (
    AdminOrEmployeeJWTAuthentication,
    IsAdminOrHR,
    resolve_company_for_user,
    actor_label,
)

from .models import (
    InsurancePolicy,
    InsuranceDependent,
    InsuranceTPA,
    NetworkHospital,
    InsuranceClaim,
    ClaimDocument,
)

from .serializers import (
    InsurancePolicySerializer,
    InsuranceDependentSerializer,
    InsuranceTPASerializer,
    NetworkHospitalSerializer,
    InsuranceClaimSerializer,
    ClaimDocumentSerializer,
)



from rest_framework.permissions import BasePermission, SAFE_METHODS

from Company.models import company_details
from Employee.models import EmployeeDT
from Employee.employee_crud_permissions import (
    resolve_company_for_user,
    role_allows,
)


class IsCompanyAdminOrInsuranceHR(BasePermission):
    """
    Company Admin:
        Full access to insurance APIs for their company.

    HR:
        Full insurance access when the active employee account
        has an active HR role belonging to the same company.

    Other employees:
        Access only when their insurance role permissions allow it.
    """

    message = "You do not have permission to perform this insurance action."

    HR_ROLE_CODES = {
        "hr",
        "hr_manager",
        "human_resource",
        "human_resources",
    }

    def has_permission(self, request, view):
        user = request.user

        company = resolve_company_for_user(user)
        if company is None:
            return False

        # Company Admin retains existing access.
        if isinstance(user, company_details):
            return True

        if not isinstance(user, EmployeeDT):
            return False

        if not getattr(user, "is_active", False):
            return False

        # Employee login details and role are stored on EmployeeAccount.
        account = getattr(user, "account", None)

        if account is None:
            return False

        if not getattr(account, "is_active", False):
            return False

        if not getattr(account, "is_login_enabled", False):
            return False

        role = getattr(account, "role", None)

        # Support existing integrations that attach role to the employee.
        if role is None:
            role = getattr(user, "role", None)

        if role is None:
            return False

        if not getattr(role, "is_active", False):
            return False

        # Never allow a role from another company.
        role_company_id = getattr(role, "company_id", None)

        if (
            role_company_id is not None
            and role_company_id != user.company_id
        ):
            return False

        role_code = str(
            getattr(role, "role_code", "")
        ).strip().lower().replace("-", "_").replace(" ", "_")

        role_name = str(
            getattr(role, "role_name", "")
        ).strip().lower()

        # Give the active HR role full access to the insurance module.
        is_hr_role = (
            role_code in self.HR_ROLE_CODES
            or role_name in {
                "hr",
                "hr manager",
                "hr admin",
                "human resources",
                "human resource",
            }
        )

        if is_hr_role:
            return True
        # Other employee roles continue using the existing permission flags.
        action = None

        action_map = getattr(view, "permission_action_map", {}) or {}
        view_action = getattr(view, "action", None)

        if 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:
            if request.method in SAFE_METHODS:
                action = "view"
            elif request.method == "POST":
                action = "create"
            elif request.method in ("PUT", "PATCH"):
                action = "edit"
            elif request.method == "DELETE":
                action = "delete"   

        if action is None:
            return False

        return role_allows(role, "insurance", action)
# ============================================================
# BASE INSURANCE VIEWSET
# ============================================================

class InsuranceBaseViewSet(ModelViewSet):

    authentication_classes = [
        AdminOrEmployeeJWTAuthentication,
    ]

    permission_classes = [
        IsCompanyAdminOrInsuranceHR,
    ]

    permission_module = "insurance"

    def get_company(self):

        company = resolve_company_for_user(
            self.request.user
        )

        if company is None:

            from rest_framework.exceptions import (
                PermissionDenied
            )

            raise PermissionDenied(
                "Unable to resolve your company."
            )

        return company

    def get_queryset(self):

        return self.queryset.filter(
            company=self.get_company()
        )

    def get_serializer_context(self):

        context = super().get_serializer_context()

        request = context.get("request")

        if request is not None:
            request.company_context = (
                self.get_company()
            )

        return context

    def perform_create(self, serializer):

        serializer.save(
            company=self.get_company(),
            created_by=actor_label(
                self.request.user
            ),
            updated_by=actor_label(
                self.request.user
            ),
        )

    def perform_update(self, serializer):

        serializer.save(
            company=self.get_company(),
            updated_by=actor_label(
                self.request.user
            ),
        )


# ============================================================
# INSURANCE POLICY
# ============================================================

class InsurancePolicyViewSet(
    InsuranceBaseViewSet
):

    queryset = InsurancePolicy.objects.all()

    serializer_class = (
        InsurancePolicySerializer
    )


# ============================================================
# INSURANCE DEPENDENT
# ============================================================

class InsuranceDependentViewSet(
    InsuranceBaseViewSet
):

    queryset = (
        InsuranceDependent.objects
        .select_related("employee")
        .all()
    )

    serializer_class = (
        InsuranceDependentSerializer
    )


# ============================================================
# INSURANCE TPA
# ============================================================

class InsuranceTPAViewSet(
    InsuranceBaseViewSet
):

    queryset = InsuranceTPA.objects.all()

    serializer_class = (
        InsuranceTPASerializer
    )


# ============================================================
# NETWORK HOSPITAL
# ============================================================

class NetworkHospitalViewSet(
    InsuranceBaseViewSet
):

    queryset = NetworkHospital.objects.all()

    serializer_class = (
        NetworkHospitalSerializer
    )


# ============================================================
# INSURANCE CLAIM
# EXISTING / LEGACY CLAIM API
# ============================================================

class InsuranceClaimViewSet(
    InsuranceBaseViewSet
):

    queryset = (
        InsuranceClaim.objects
        .select_related(
            "employee",
            "policy",
        )
        .prefetch_related(
            "documents",
        )
        .all()
    )

    serializer_class = (
        InsuranceClaimSerializer
    )

    permission_action_map = {
        "approve": "approve",
        "reject": "approve",
        "settle": "approve",
        "reopen": "edit",
    }

    # --------------------------------------------------------
    # APPROVE
    # --------------------------------------------------------

    @action(
        detail=True,
        methods=["post"],
    )
    def approve(
        self,
        request,
        pk=None,
    ):

        claim = self.get_object()

        if claim.status != "Pending":

            return Response(
                {
                    "detail": (
                        "Only Pending claims "
                        "can be approved."
                    )
                },
                status=status.HTTP_400_BAD_REQUEST,
            )

        approved_amount = request.data.get(
            "approved_amount"
        )

        if approved_amount is None:

            return Response(
                {
                    "approved_amount":
                        "This field is required."
                },
                status=status.HTTP_400_BAD_REQUEST,
            )

        try:

            approved_amount = float(
                approved_amount
            )

        except (
            ValueError,
            TypeError,
        ):

            return Response(
                {
                    "approved_amount":
                        "Invalid amount."
                },
                status=status.HTTP_400_BAD_REQUEST,
            )

        if approved_amount < 0:

            return Response(
                {
                    "approved_amount":
                        "Amount cannot be negative."
                },
                status=status.HTTP_400_BAD_REQUEST,
            )

        if (
            approved_amount
            > float(claim.claimed_amount)
        ):

            return Response(
                {
                    "approved_amount":
                        "Amount cannot exceed claim amount."
                },
                status=status.HTTP_400_BAD_REQUEST,
            )

        claim.approved_amount = (
            approved_amount
        )

        claim.status = "Approved"

        claim.approved_at = (
            timezone.now()
        )

        claim.approved_by = (
            actor_label(request.user)
        )

        claim.tpa_ref = request.data.get(
            "tpa_ref",
            claim.tpa_ref,
        )

        claim.remarks = request.data.get(
            "remarks",
            claim.remarks,
        )

        claim.updated_by = (
            actor_label(request.user)
        )

        claim.save()

        return Response(
            self.get_serializer(
                claim
            ).data,
            status=status.HTTP_200_OK,
        )

    # --------------------------------------------------------
    # REJECT
    # --------------------------------------------------------

    @action(
        detail=True,
        methods=["post"],
    )
    def reject(
        self,
        request,
        pk=None,
    ):

        claim = self.get_object()

        if claim.status not in [
            "Pending",
            "Approved",
        ]:

            return Response(
                {
                    "detail": (
                        "Only Pending or Approved "
                        "claims can be rejected."
                    )
                },
                status=status.HTTP_400_BAD_REQUEST,
            )

        claim.status = "Rejected"

        claim.rejection_category = (
            request.data.get(
                "category",
                "Other",
            )
        )

        claim.rejection_reason = (
            request.data.get(
                "notes",
                "",
            )
        )

        claim.rejected_at = (
            timezone.now()
        )

        claim.rejected_by = (
            actor_label(request.user)
        )

        claim.updated_by = (
            actor_label(request.user)
        )

        claim.save()

        return Response(
            self.get_serializer(
                claim
            ).data,
            status=status.HTTP_200_OK,
        )

    # --------------------------------------------------------
    # REOPEN
    # --------------------------------------------------------

    @action(
        detail=True,
        methods=["post"],
    )
    def reopen(
        self,
        request,
        pk=None,
    ):

        claim = self.get_object()

        if claim.status != "Rejected":

            return Response(
                {
                    "detail": (
                        "Only Rejected claims "
                        "can be reopened."
                    )
                },
                status=status.HTTP_400_BAD_REQUEST,
            )

        claim.status = "Pending"

        claim.rejection_category = ""

        claim.rejection_reason = ""

        claim.reopened_at = (
            timezone.now()
        )

        claim.reopened_by = (
            actor_label(request.user)
        )

        claim.updated_by = (
            actor_label(request.user)
        )

        claim.save()

        return Response(
            self.get_serializer(
                claim
            ).data,
            status=status.HTTP_200_OK,
        )


# ============================================================
# CLAIM DOCUMENT
# ============================================================

class ClaimDocumentViewSet(
    InsuranceBaseViewSet
):

    queryset = (
        ClaimDocument.objects
        .select_related("claim")
        .all()
    )

    serializer_class = (
        ClaimDocumentSerializer
    )