"""Shared helpers for API route modules."""

from typing import TypeVar

from fastapi import HTTPException
from sqlmodel import SQLModel
from sqlmodel.ext.asyncio.session import AsyncSession

T = TypeVar("T", bound=SQLModel)


async def get_owned_entity(
    session: AsyncSession,
    model: type[T],
    entity_id: int,
    user_id: int,
    *,
    owner_field: str = "user_id",
    not_found_msg: str = "Not found",
) -> T:
    """Fetch an entity by PK and verify ownership, or raise 404."""
    entity = await session.get(model, entity_id)
    if not entity or getattr(entity, owner_field) != user_id:
        raise HTTPException(status_code=404, detail=not_found_msg)
    return entity
