"""Doctor panel validators — Phase 13.2."""
from __future__ import annotations

from app.models.types import VisitSessionAction, VisitSessionStatus
from shared.exceptions import AppError

ALLOWED: dict[VisitSessionAction, set[VisitSessionStatus]] = {
    VisitSessionAction.CALL_NEXT: {VisitSessionStatus.QUEUED},
    VisitSessionAction.START: {VisitSessionStatus.QUEUED},
    VisitSessionAction.FINISH: {VisitSessionStatus.IN_PROGRESS},
    VisitSessionAction.DEFER: {VisitSessionStatus.QUEUED, VisitSessionStatus.IN_PROGRESS},
}
TARGET: dict[VisitSessionAction, VisitSessionStatus] = {
    VisitSessionAction.CALL_NEXT: VisitSessionStatus.QUEUED,
    VisitSessionAction.START: VisitSessionStatus.IN_PROGRESS,
    VisitSessionAction.FINISH: VisitSessionStatus.COMPLETED,
    VisitSessionAction.DEFER: VisitSessionStatus.DEFERRED,
}
TERMINAL = frozenset({VisitSessionStatus.COMPLETED, VisitSessionStatus.CANCELLED})


def ensure_visit_session_transition(
    *, action: VisitSessionAction, current: VisitSessionStatus
) -> None:
    if current in TERMINAL:
        raise AppError(
            "جلسه ویزیت در وضعیت پایانی است",
            status_code=409,
            error_code="visit_session_terminal",
        )
    allowed = ALLOWED.get(action, set())
    if current not in allowed:
        raise AppError(
            "انتقال وضعیت جلسه ویزیت مجاز نیست",
            status_code=409,
            error_code="invalid_visit_session_transition",
            details={"from_status": current.value, "action": action.value},
        )


def target_status_for(action: VisitSessionAction) -> VisitSessionStatus:
    return TARGET[action]
