from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from src.db.models.form_type import FormTypeEnum
from src.db.models.expense_item import ExpenseItem, ExpenseItemFormType


class ExpenseItemRepository:
    def __init__(self, db: AsyncSession):
        self.db = db

    async def get(self, item_id: int) -> ExpenseItem | None:
        query = select(ExpenseItem).where(ExpenseItem.id == item_id).limit(1)
        return (await self.db.execute(query)).scalar_one_or_none()
    
    async def get_list(
            self, 
            r_start: bool | None = None,
            sheet: str | None = None,
            direction: str | None = None,
            form_type: FormTypeEnum | str | None = None,
    ) -> list[ExpenseItem]:
        where = []
        query = select(ExpenseItem)
        if form_type is not None:
            query = query.join(
                ExpenseItemFormType, 
                ExpenseItemFormType.expense_item_id == ExpenseItem.id,
            ).where(
                ExpenseItemFormType.form_type_code == (form_type.value if isinstance(form_type, FormTypeEnum) else form_type)
            )
        if r_start is not None:
            where.append(ExpenseItem.item_id.startswith("R"))
        if sheet is not None:
            where.append(ExpenseItem.sheet == sheet)
        if direction is not None:
            where.append(ExpenseItem.direction == direction)
        query = query.where(*where)



        
        return (await self.db.execute(query)).scalars().all()
