from sqlalchemy.orm import Session

from app.core.logging import get_logger
from app.models.reimbursement import ReimbursementRequest
from app.repositories.reimbursement import ReimbursementRepository
from app.schemas.reimbursement import ReimbursementCreate
from app.services.pagination import PageResult

logger = get_logger("app.services.reimbursement")


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

    def list_reimbursements(self) -> list[ReimbursementRequest]:
        items = self.repository.list()
        logger.info("Listed reimbursements (count=%d)", len(items))
        return items

    def list_reimbursements_page(
        self,
        *,
        page: int | None,
        page_size: int | None,
    ) -> PageResult[ReimbursementRequest]:
        result = self.repository.list_page(page=page, page_size=page_size)
        logger.info(
            "Listed reimbursements page (count=%d, total=%d, page=%d, page_size=%d)",
            len(result.items),
            result.total,
            result.page,
            result.page_size,
        )
        return result

    def get_reimbursement(self, request_id: str) -> ReimbursementRequest | None:
        request = self.repository.get(request_id)
        if request:
            logger.info("Fetched reimbursement id=%s no=%s", request_id, request.request_no)
        else:
            logger.warning("Reimbursement not found id=%s", request_id)
        return request

    def create_reimbursement(self, payload: ReimbursementCreate) -> ReimbursementRequest:
        request = ReimbursementRequest(**payload.model_dump(), status="draft")
        created = self.repository.create(request)
        logger.info(
            "Created reimbursement id=%s no=%s amount=%s",
            created.id,
            created.request_no,
            created.amount,
        )
        return created
