"""admin 埋点日志:列表 + 按事件 / 设备 / 用户 / 会话 / 时间筛选(只读,同库直接查 analytics_event)。"""
from __future__ import annotations

from datetime import datetime
from typing import Annotated

from fastapi import APIRouter, Depends, Query

from app.admin.deps import AdminDb, require_page
from app.admin.repositories import queries
from app.admin.schemas.analytics import AnalyticsEventOut
from app.admin.schemas.common import CursorPage

router = APIRouter(
    prefix="/admin/api/event-logs",
    tags=["admin-event-logs"],
    dependencies=[Depends(require_page("event-logs"))],
)


@router.get("", response_model=CursorPage[AnalyticsEventOut], summary="埋点日志列表")
def list_event_logs(
    db: AdminDb,
    event: Annotated[str | None, Query(max_length=64)] = None,
    device_id: Annotated[str | None, Query(max_length=64)] = None,
    user_id: Annotated[int | None, Query()] = None,
    session_id: Annotated[str | None, Query(max_length=64)] = None,
    created_from: Annotated[datetime | None, Query()] = None,
    created_to: Annotated[datetime | None, Query()] = None,
    sort_by: Annotated[str, Query(pattern="^(id|created_at)$")] = "id",
    sort_order: Annotated[str, Query(pattern="^(asc|desc)$")] = "desc",
    limit: Annotated[int, Query(ge=1, le=100)] = 20,
    cursor: Annotated[int | None, Query()] = None,
) -> CursorPage[AnalyticsEventOut]:
    items, next_cursor, total = queries.list_analytics_events(
        db,
        event=event,
        device_id=device_id,
        user_id=user_id,
        session_id=session_id,
        created_from=created_from,
        created_to=created_to,
        sort_by=sort_by,
        sort_order=sort_order,
        limit=limit,
        cursor=cursor,
    )
    return CursorPage(
        items=[AnalyticsEventOut.model_validate(e) for e in items],
        next_cursor=next_cursor,
        total=total,
    )
