# #region approval_repository [C:3] [TYPE Module] [SEMANTICS clean-release, approval, repository, persistence, crud]
# @BRIEF Persist and query approval decisions.
# @LAYER Infrastructure
# @RELATION DEPENDS_ON -> [EXT:Library:sqlalchemy]


from sqlalchemy.orm import Session

from src.core.logger import belief_scope
from src.models.clean_release import ApprovalDecision


class ApprovalRepository:
    """
    @PURPOSE: Encapsulates database operations for ApprovalDecision.
    """
    def __init__(self, db: Session):
        self.db = db

    def save(self, decision: ApprovalDecision) -> ApprovalDecision:
        """
        @PURPOSE: Persist an approval decision.
        @POST: Decision is committed and refreshed.
        """
        with belief_scope("ApprovalRepository.save"):
            self.db.add(decision)
            self.db.commit()
            self.db.refresh(decision)
            return decision

    def get_by_id(self, decision_id: str) -> ApprovalDecision | None:
        """
        @PURPOSE: Retrieve a decision by ID.
        """
        with belief_scope("ApprovalRepository.get_by_id"):
            return self.db.query(ApprovalDecision).filter(ApprovalDecision.id == decision_id).first()

    def get_latest_for_candidate(self, candidate_id: str) -> ApprovalDecision | None:
        """
        @PURPOSE: Retrieve the latest decision for a candidate.
        """
        with belief_scope("ApprovalRepository.get_latest_for_candidate"):
            return self.db.query(ApprovalDecision)\
                .filter(ApprovalDecision.candidate_id == candidate_id)\
                .order_by(ApprovalDecision.decided_at.desc())\
                .first()

    def list_by_candidate(self, candidate_id: str) -> list[ApprovalDecision]:
        """
        @PURPOSE: List all decisions for a specific candidate.
        """
        with belief_scope("ApprovalRepository.list_by_candidate"):
            return self.db.query(ApprovalDecision).filter(ApprovalDecision.candidate_id == candidate_id).all()

# #endregion approval_repository
