"""Event routes."""

from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy.orm import Session

from app.core.db import get_db
from app.schemas.event import EventCreate, EventRead
from app.services import engagements as engagement_service
from app.services import events as event_service

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


@router.post("", response_model=EventRead, status_code=status.HTTP_201_CREATED)
def create_event(payload: EventCreate, db: Session = Depends(get_db)) -> EventRead:
    """Create one event."""
    try:
        return event_service.create_event(db, payload)
    except LookupError as exc:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc


@router.get("", response_model=list[EventRead])
def list_events(
    engagement_id: int | None = Query(default=None, ge=1),
    db: Session = Depends(get_db),
) -> list[EventRead]:
    """List events sorted by newest timestamp first."""
    if engagement_id is not None and engagement_service.get_engagement_by_id(db, engagement_id) is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="engagement not found",
        )

    return event_service.list_events(db, engagement_id=engagement_id)


@router.get("/{event_id}", response_model=EventRead)
def get_event(event_id: int, db: Session = Depends(get_db)) -> EventRead:
    """Get one event by id."""
    event = event_service.get_event_by_id(db, event_id)
    if event is None:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="event not found")
    return event
