from django.db import transaction
from django.utils import timezone

from apps.accounts_rbac.constants import Permissions
from apps.accounts_rbac.models import CompanyMembership, User
from apps.notifications.models import ConfirmationAudit, Notification, NotificationRecipientState
from apps.tenancy.models import Company


class ConfirmationWorkflowService:
    """Server-side audit & phrase/authority enforcement for high-impact confirmations."""

    @staticmethod
    def record_audit(
        *,
        company: Company | None,
        actor: User,
        action_type: str,
        source_object_type: str = "",
        source_object_id: str = "",
        source_reference: str = "",
        confirmation_phrase_used: str = "",
        required_phrase: str = "",
        second_approver_id=None,
        execution_result: str = "SUCCESS",
        detail: str = "",
    ) -> ConfirmationAudit:
        auth_ok = True
        if required_phrase and confirmation_phrase_used.strip() != required_phrase.strip():
            auth_ok = False
        audit = ConfirmationAudit.objects.create(
            company=company,
            actor=actor,
            action_type=action_type[:64],
            source_object_type=source_object_type[:64],
            source_object_id=str(source_object_id or "")[:64],
            source_reference=source_reference[:128],
            confirmation_phrase_used=confirmation_phrase_used[:128],
            second_approver_id=second_approver_id,
            authorization_result="ALLOWED" if auth_ok else "DENIED",
            execution_result=execution_result if auth_ok else "FAILED",
            detail=detail,
        )
        if not auth_ok:
            raise PermissionError(f"Confirmation phrase mismatch. Expected exact phrase '{required_phrase}'.")
        return audit


class NotificationActionService:
    """
    Validates & dispatches permitted actions directly from a persisted Notification record.
    Never executes arbitrary client-supplied commands; always revalidates recipient ownership,
    RBAC permission, data scope, and current source object state (blocking stale duplicates with 409).
    """

    SUPPORTED_ACTIONS = {
        "APPROVE_VOUCHER",
        "REJECT_VOUCHER",
        "POST_VOUCHER",
        "APPROVE_PROFILE_CHANGE",
        "REJECT_PROFILE_CHANGE",
        "ACKNOWLEDGE_ALERT",
        "OPEN_CHAT",
        "NAVIGATE",
    }

    @staticmethod
    @transaction.atomic
    def execute_action(
        *,
        notif: Notification,
        user: User,
        company: Company,
        action_key: str,
        comment: str = "",
    ) -> dict:
        if notif.recipient_id != user.id:
            raise PermissionError("Cannot execute an action on another user's notification.")
        if notif.company_id and str(notif.company_id) != str(company.id):
            raise PermissionError("Notification belongs to a different company context.")

        mem = CompanyMembership.objects.select_related("role").prefetch_related("roles", "projects").filter(
            user=user, company=company, is_active=True
        ).first()
        if not mem and not user.is_superuser:
            raise PermissionError("No active membership in target company.")

        perms = set(mem.effective_permissions()) if mem else set()
        if not user.is_superuser and Permissions.NOTIFICATION_ACTION_EXECUTE not in perms:
            raise PermissionError("Missing notification.action_execute permission.")

        allowed_in_record = [
            a.get("key") for a in (notif.action_definition or {}).get("actions", []) if isinstance(a, dict)
        ]
        # Allow ACKNOWLEDGE_ALERT / OPEN_CHAT / NAVIGATE if declared or explicit
        if action_key not in NotificationActionService.SUPPORTED_ACTIONS:
            raise ValueError(f"Unsupported notification action '{action_key}'.")
        if allowed_in_record and action_key not in allowed_in_record and action_key != "ACKNOWLEDGE_ALERT":
            raise PermissionError(f"Action '{action_key}' is not authorized for this notification.")

        if notif.status in (Notification.Status.STALE, Notification.Status.EXECUTED, Notification.Status.EXPIRED):
            raise LookupError("STALE_NOTIFICATION: This notification has already been handled or superseded.")

        state, _ = NotificationRecipientState.objects.get_or_create(notification=notif, recipient=user)

        if action_key == "ACKNOWLEDGE_ALERT":
            state.acknowledged_at = timezone.now()
            state.is_read = True
            state.read_at = state.read_at or timezone.now()
            state.executed_action = action_key
            state.executed_at = timezone.now()
            state.save()
            return {"status": "acknowledged", "notification_id": str(notif.id)}

        if action_key == "OPEN_CHAT":
            conv_id = (notif.metadata or {}).get("conversation_id") or notif.source_object_id
            state.is_read = True
            state.read_at = state.read_at or timezone.now()
            state.save(update_fields=["is_read", "read_at"])
            return {"status": "open_chat", "conversation_id": str(conv_id)}

        if action_key in ("APPROVE_VOUCHER", "REJECT_VOUCHER", "POST_VOUCHER"):
            from apps.accounting.models import Voucher
            from apps.accounting.services.core import ApprovalService, PostingService

            voucher = Voucher.objects.filter(company=company, id=notif.source_object_id).first()
            if not voucher:
                notif.status = Notification.Status.STALE
                notif.save(update_fields=["status"])
                raise LookupError("STALE_NOTIFICATION: Target voucher no longer exists.")

            if action_key == "APPROVE_VOUCHER":
                if not user.is_superuser and Permissions.VOUCHER_APPROVE not in perms:
                    raise PermissionError("Missing voucher.approve permission.")
                if voucher.status not in (Voucher.Status.SUBMITTED, Voucher.Status.UNDER_REVIEW):
                    notif.status = Notification.Status.STALE
                    notif.save(update_fields=["status"])
                    raise LookupError(f"STALE_NOTIFICATION: Voucher is already in status {voucher.status}.")
                updated = ApprovalService.approve_voucher(voucher=voucher, user=user, comment=comment)
                ConfirmationWorkflowService.record_audit(
                    company=company,
                    actor=user,
                    action_type="APPROVE_VOUCHER",
                    source_object_type="Voucher",
                    source_object_id=str(voucher.id),
                    source_reference=voucher.voucher_no or str(voucher.id),
                    detail=comment,
                )
            elif action_key == "REJECT_VOUCHER":
                if not user.is_superuser and Permissions.VOUCHER_REJECT not in perms:
                    raise PermissionError("Missing voucher.reject permission.")
                if voucher.status not in (Voucher.Status.SUBMITTED, Voucher.Status.UNDER_REVIEW, Voucher.Status.APPROVED):
                    notif.status = Notification.Status.STALE
                    notif.save(update_fields=["status"])
                    raise LookupError(f"STALE_NOTIFICATION: Voucher is already in status {voucher.status}.")
                updated = ApprovalService.reject_voucher(voucher=voucher, user=user, reason=comment or "Rejected via Notification Center")
            else:
                if not user.is_superuser and Permissions.VOUCHER_POST not in perms:
                    raise PermissionError("Missing voucher.post permission.")
                if voucher.status != Voucher.Status.APPROVED:
                    notif.status = Notification.Status.STALE
                    notif.save(update_fields=["status"])
                    raise LookupError(f"STALE_NOTIFICATION: Voucher must be APPROVED before posting (currently {voucher.status}).")
                updated = PostingService.post_voucher(voucher=voucher, user=user)

            notif.status = Notification.Status.EXECUTED
            notif.save(update_fields=["status"])
            state.is_read = True
            state.read_at = timezone.now()
            state.executed_action = action_key
            state.executed_at = timezone.now()
            state.save()
            return {
                "status": "executed",
                "action": action_key,
                "voucher_id": str(updated.id),
                "voucher_no": updated.voucher_no,
                "voucher_status": updated.status,
            }

        if action_key in ("APPROVE_PROFILE_CHANGE", "REJECT_PROFILE_CHANGE"):
            from apps.hr.models import StaffProfileChangeRequest
            from apps.hr.staff_services import StaffProfileChangeService

            req_obj = StaffProfileChangeRequest.objects.filter(company=company, id=notif.source_object_id).first()
            if not req_obj or req_obj.status != "PENDING":
                notif.status = Notification.Status.STALE
                notif.save(update_fields=["status"])
                raise LookupError("STALE_NOTIFICATION: Profile change request is no longer pending.")
            if not user.is_superuser and Permissions.HR_PROFILE_APPROVE not in perms:
                raise PermissionError("Missing hr.profile_approve permission.")
            if action_key == "APPROVE_PROFILE_CHANGE":
                StaffProfileChangeService.approve_request(company=company, request_id=str(req_obj.id), reviewer=user, comment=comment)
            else:
                StaffProfileChangeService.reject_request(company=company, request_id=str(req_obj.id), reviewer=user, comment=comment)
            notif.status = Notification.Status.EXECUTED
            notif.save(update_fields=["status"])
            state.is_read = True
            state.read_at = timezone.now()
            state.executed_action = action_key
            state.executed_at = timezone.now()
            state.save()
            return {"status": "executed", "action": action_key}

        return {"status": "navigate", "route_key": notif.route_key}

