"""Engagement business logic."""

from __future__ import annotations

from sqlalchemy import select
from sqlalchemy.orm import Session

from app.models.engagement import Engagement
from app.schemas.engagement import EngagementCreate
from app.services.coverage import create_initial_coverage


def create_engagement(db: Session, payload: EngagementCreate) -> Engagement:
    """Create an engagement and initialize its coverage row."""
    existing = db.scalar(select(Engagement).where(Engagement.name == payload.name))
    if existing is not None:
        raise ValueError("engagement name already exists")

    engagement = Engagement(
        name=payload.name,
        description=payload.description,
        metadata_json=payload.metadata,
    )
    db.add(engagement)
    db.flush()

    create_initial_coverage(db, engagement.id)
    db.commit()
    db.refresh(engagement)
    return engagement


def list_engagements(db: Session) -> list[Engagement]:
    """List all engagements ordered by newest first."""
    result = db.scalars(
        select(Engagement).order_by(Engagement.created_at.desc(), Engagement.id.desc()),
    )
    return list(result.all())


def get_engagement_by_id(db: Session, engagement_id: int) -> Engagement | None:
    """Fetch one engagement by id."""
    return db.scalar(select(Engagement).where(Engagement.id == engagement_id))


def require_engagement(db: Session, engagement_id: int) -> Engagement:
    """Return engagement or raise lookup error."""
    engagement = get_engagement_by_id(db, engagement_id)
    if engagement is None:
        raise LookupError("engagement not found")
    return engagement
