"""Category endpoints."""

from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from app.api.deps import get_user_id, get_db_session
from app.models import Category

router = APIRouter(prefix="/api/categories", tags=["categories"])


class CategoryOut(BaseModel):
    id: int
    title: str

    class Config:
        from_attributes = True


class CategoryCreate(BaseModel):
    title: str


@router.get("", response_model=list[CategoryOut])
async def list_categories(
    user_id: str = Depends(get_user_id),
    db: AsyncSession = Depends(get_db_session),
):
    result = await db.execute(
        select(Category)
        .where(Category.user_id == user_id)
        .order_by(Category.title)
    )
    return result.scalars().all()


@router.post("", response_model=CategoryOut, status_code=201)
async def create_category(
    body: CategoryCreate,
    user_id: str = Depends(get_user_id),
    db: AsyncSession = Depends(get_db_session),
):
    cat = Category(user_id=user_id, title=body.title)
    db.add(cat)
    await db.commit()
    await db.refresh(cat)
    return cat
