"""
PPM Infrastructure — CashFlowProjection Repository Implementation

پیاده‌سازی ریپازیتوری پیش‌بینی جریان نقدی با Django ORM.
"""

from typing import Optional, List
from uuid import UUID

from ...domain.entities.business_case import CashFlowProjection
from ...domain.repositories.interfaces import ICashFlowProjectionRepository
from ..persistence.models import CashFlowProjectionModel
from .mappers import CashFlowProjectionMapper


class DjangoCashFlowProjectionRepository(ICashFlowProjectionRepository):
    """پیاده‌سازی ریپازیتوری پیش‌بینی جریان نقدی."""

    def save(self, entity: CashFlowProjection) -> CashFlowProjection:
        try:
            model = CashFlowProjectionModel.objects.get(id=entity.id)
            model = CashFlowProjectionMapper.to_model(entity, model)
        except CashFlowProjectionModel.DoesNotExist:
            model = CashFlowProjectionMapper.to_model(entity)
        model.save()
        return CashFlowProjectionMapper.to_entity(model)

    def get_by_id(self, id: UUID) -> Optional[CashFlowProjection]:
        try:
            model = CashFlowProjectionModel.objects.get(id=id)
            return CashFlowProjectionMapper.to_entity(model)
        except CashFlowProjectionModel.DoesNotExist:
            return None

    def find(self, **filters) -> List[CashFlowProjection]:
        qs = CashFlowProjectionModel.objects.filter(**filters)
        return [CashFlowProjectionMapper.to_entity(m) for m in qs]

    def delete(self, id: UUID) -> None:
        CashFlowProjectionModel.objects.filter(id=id).delete()

    def find_by_business_case(self, business_case_id: UUID) -> List[CashFlowProjection]:
        return self.find(business_case_id=business_case_id)
