from datetime import timedelta

from fastapi import APIRouter, Depends
from sqlalchemy import delete
from sqlalchemy.ext.asyncio import AsyncSession

from .... import settings
from ....auth_security import AdminContext, require_admin
from ....db import get_session
from ....model_defs.l2a_models import L2ABulkJob, L2ASuggestion
from ..l2a import utcnow


router = APIRouter(prefix="/api/v2/admin", tags=["admin"])


@router.post("/maintenance/purge_jobs", dependencies=[Depends(require_admin)])
async def purge_jobs(
    _admin: AdminContext,
    db: AsyncSession = Depends(get_session),
) -> dict:
    """
    Purge L2A bulk jobs and suggestions older than the retention window.
    Only removes suggestions that have a terminal status (linked/rejected/error).
    """
    cutoff = utcnow() - timedelta(days=settings.L2A_JOB_RETENTION_DAYS)

    await db.execute(delete(L2ABulkJob).where(L2ABulkJob.created_at < cutoff))
    await db.execute(
        delete(L2ASuggestion).where(
            L2ASuggestion.status.in_(["linked", "rejected", "error"]),
            L2ASuggestion.decided_at.isnot(None),
            L2ASuggestion.decided_at < cutoff,
        )
    )
    await db.commit()
    return {"ok": True}
