from fastapi import APIRouter, Query
import database as db
from typing import Any
from logger import get_logger
logger = get_logger(__name__)

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


@router.get("/{incident_id}")
def get_incident(incident_id: int) -> dict[str, Any] | None:
    conn = db.connect_to_db()
    try:
        return db.get_incident_by_id(conn, incident_id)
    except Exception as e:
        logger.error(f"Error fetching incident {incident_id}: {e}", exc_info=True)
        return None
    finally:
        conn.close()


@router.get("/")
def get_incidents(
    id: int | None = Query(None),
    before: int | None = Query(None)
) -> list[dict[str, Any]]:
    conn = db.connect_to_db()
    try:
        return db.get_incidents(conn, id=id, before=before)
    except Exception as e:
        logger.error(f"Error fetching incidents (id={id}, before={before}): {e}", exc_info=True)
        return []
    finally:
        conn.close()
