"""Engagement routes."""

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

from app.core.db import get_db
from app.schemas.engagement import EngagementCreate, EngagementRead
from app.services import engagements as engagement_service

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


@router.post("", response_model=EngagementRead, status_code=status.HTTP_201_CREATED)
def create_engagement(payload: EngagementCreate, db: Session = Depends(get_db)) -> EngagementRead:
    """Create an engagement."""
    try:
        return engagement_service.create_engagement(db, payload)
    except ValueError as exc:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc


@router.get("", response_model=list[EngagementRead])
def list_engagements(db: Session = Depends(get_db)) -> list[EngagementRead]:
    """List engagements."""
    return engagement_service.list_engagements(db)


@router.get("/{engagement_id}", response_model=EngagementRead)
def get_engagement(engagement_id: int, db: Session = Depends(get_db)) -> EngagementRead:
    """Get one engagement by id."""
    engagement = engagement_service.get_engagement_by_id(db, engagement_id)
    if engagement is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="engagement not found",
        )
    return engagement
