from sqlalchemy import select
from sqlalchemy.orm import Session

from app.models.reimbursement import ReimbursementRequest
from app.services.pagination import PageResult, paginate_select


class ReimbursementRepository:
    def __init__(self, db: Session) -> None:
        self.db = db

    def _list_stmt(self):
        return select(ReimbursementRequest).order_by(ReimbursementRequest.created_at.desc())

    def list(self) -> list[ReimbursementRequest]:
        return list(self.db.scalars(self._list_stmt()).all())

    def list_page(
        self,
        *,
        page: int | None,
        page_size: int | None,
    ) -> PageResult[ReimbursementRequest]:
        return paginate_select(self.db, self._list_stmt(), page=page, page_size=page_size)

    def get(self, request_id: str) -> ReimbursementRequest | None:
        return self.db.query(ReimbursementRequest).filter(ReimbursementRequest.id == request_id).first()

    def create(self, request: ReimbursementRequest) -> ReimbursementRequest:
        self.db.add(request)
        self.db.commit()
        self.db.refresh(request)
        return request
