
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession

from src.db.models.form_type import FormTypeEnum
from src.services.expense_item_service import ExpenseItemService
from src.db.models.app_user import AppUser
from src.api.v1.deps import require_admin, require_executor
from src.db.session import get_db
from src.domain.schemas import (
    BaseListResponse,
    BaseSingleResponse,
    ExpenseItemResponseSchema,
)

router = APIRouter(prefix="/expense-item", tags=["expense-item"])


@router.get("/{item_id}", response_model=BaseSingleResponse[ExpenseItemResponseSchema])
async def get_expense_item_by_id(
    item_id: int,
    db: AsyncSession = Depends(get_db),
    current_user: AppUser = Depends(require_admin),
):
    """Получение записи expense item по ID."""
    service = ExpenseItemService(db)
    result = await service.get(item_id, user=current_user)
    if not result:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Expense Item не найден",
        )
    return BaseSingleResponse(
        success=True,
        message="Запись Expense Item",
        result=ExpenseItemResponseSchema.model_validate(result),
    )


@router.get("/", response_model=BaseListResponse[ExpenseItemResponseSchema])
async def get_expense_item_by_id(
    db: AsyncSession = Depends(get_db),
    current_user: AppUser = Depends(require_executor),
    r_start: bool | None = None,
    sheet: str | None = None,
    direction: str | None = None,
    form_type: FormTypeEnum | str | None = None
):
    """Получение записей expense item"""
    service = ExpenseItemService(db)
    result = await service.get_list(
        r_start=r_start,
        sheet=sheet,
        direction=direction,
        form_type=form_type,
    )

    return BaseListResponse(
        success=True,
        message="Запись Expense Item",
        result=[ExpenseItemResponseSchema.model_validate(el) for el in result],
    )
