"""Event business logic."""

from __future__ import annotations

from sqlalchemy import select
from sqlalchemy.orm import Session

from app.models.event import Event
from app.schemas.event import EventCreate
from app.services.coverage import sync_coverage_from_events
from app.services.engagements import get_engagement_by_id


def create_event(db: Session, payload: EventCreate) -> Event:
    """Create an event and update engagement coverage."""
    if get_engagement_by_id(db, payload.engagement_id) is None:
        raise LookupError("engagement not found")

    event_data = payload.model_dump(exclude_none=True)
    event = Event(**event_data)
    db.add(event)
    db.flush()

    sync_coverage_from_events(db, payload.engagement_id)
    db.commit()
    db.refresh(event)
    return event


def list_events(db: Session, engagement_id: int | None = None) -> list[Event]:
    """List events, optionally filtered by engagement id."""
    query = select(Event)
    if engagement_id is not None:
        query = query.where(Event.engagement_id == engagement_id)

    result = db.scalars(query.order_by(Event.ts.desc(), Event.id.desc()))
    return list(result.all())


def get_event_by_id(db: Session, event_id: int) -> Event | None:
    """Fetch one event by id."""
    return db.scalar(select(Event).where(Event.id == event_id))
