# [DEF:approval_repository:Module]
# @TIER: STANDARD
# @PURPOSE: Persist and query approval decisions.
# @LAYER: Infra

from typing import Optional, List
from sqlalchemy.orm import Session
from src.models.clean_release import ApprovalDecision
from src.core.logger import belief_scope

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) -> Optional[ApprovalDecision]:
        """
        @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) -> Optional[ApprovalDecision]:
        """
        @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()

# [/DEF:approval_repository:Module]