"""Playback history endpoints."""

from fastapi import APIRouter, Query, Response

from app.api.deps import CurrentUser, HistoryRepoDep, TrackRepoDep
from app.api.schemas.history import HistoryIn, HistoryOut
from app.api.schemas.pagination import PagedResponse
from app.domain.errors import NotFoundError

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


@router.post("", status_code=204)
async def record_history(
    body: HistoryIn,
    history_repo: HistoryRepoDep,
    track_repo: TrackRepoDep,
    user: CurrentUser,
) -> Response:
    track = await track_repo.get_by_id(body.track_id)
    if track is None:
        raise NotFoundError(f"Track {body.track_id} not found.")
    await history_repo.add(
        user_id=user.id,
        track_id=body.track_id,
        played_at=body.played_at,
        play_duration_seconds=body.play_duration_seconds,
        completed=body.completed,
    )
    return Response(status_code=204)


@router.get("")
async def get_history(
    history_repo: HistoryRepoDep,
    user: CurrentUser,
    limit: int = Query(50, ge=1, le=200),
    offset: int = Query(0, ge=0),
) -> PagedResponse[HistoryOut]:
    entries = await history_repo.list(user_id=user.id, limit=limit, offset=offset)
    total = await history_repo.count(user_id=user.id)
    items = [
        HistoryOut(
            id=e.id,
            track_id=e.track_id,
            played_at=e.played_at,
            play_duration_seconds=e.play_duration_seconds,
            completed=e.completed,
        )
        for e in entries
    ]
    return PagedResponse(items=items, total=total, limit=limit, offset=offset)
