"""GET /api/calls — phone-call / voice-call log list. Read-only query over the mirrored ``phone_call`` table. ``channel`` here is the **call-type** in {``phone_call``, ``voice_call``} (calls are not tied to a messaging channel). Filters: ``channel``, ``user_id``, and a ms-epoch ``[start, end]`` window compared against ``start_call_time`` (inclusive). Ordered by ``start_call_time desc`` (nulls last) — most recent calls first. """ from __future__ import annotations from typing import Annotated import sqlalchemy as sa from fastapi import APIRouter, Depends, Query from sqlalchemy.ext.asyncio import AsyncSession from app.api.deps import get_session from app.api.schemas import Page, PhoneCallOut from app.db.models import PhoneCall router = APIRouter(prefix="/api", tags=["calls"]) SessionDep = Annotated[AsyncSession, Depends(get_session)] PageParam = Annotated[int, Query(ge=1)] PageSizeParam = Annotated[int, Query(ge=1, le=100)] @router.get("/calls") async def list_calls( session: SessionDep, page: PageParam = 1, page_size: PageSizeParam = 20, channel: Annotated[str | None, Query()] = None, user_id: Annotated[str | None, Query()] = None, start: Annotated[int | None, Query(ge=0)] = None, end: Annotated[int | None, Query(ge=0)] = None, ) -> Page[PhoneCallOut]: """List phone/voice calls with optional filters, newest first.""" conditions = [] if channel is not None: conditions.append(PhoneCall.channel == channel) if user_id is not None: conditions.append(PhoneCall.user_id == user_id) if start is not None: conditions.append(PhoneCall.start_call_time >= start) if end is not None: conditions.append(PhoneCall.start_call_time <= end) total_stmt = sa.select(sa.func.count()).select_from(PhoneCall) if conditions: total_stmt = total_stmt.where(*conditions) total = (await session.execute(total_stmt)).scalar_one() list_stmt = sa.select(PhoneCall) if conditions: list_stmt = list_stmt.where(*conditions) list_stmt = ( list_stmt.order_by( sa.nullslast(PhoneCall.start_call_time.desc()), PhoneCall.call_id.asc(), ) .limit(page_size) .offset((page - 1) * page_size) ) rows = (await session.execute(list_stmt)).scalars().all() items = [PhoneCallOut.model_validate(row) for row in rows] return Page(items=items, total=total, page=page, page_size=page_size)