"""CRM / Leads API — Spec 012."""

from __future__ import annotations

from fastapi import APIRouter, Depends, HTTPException, Query

from app import auth, crm_leads
from app.permissions import can_read_crm_leads

router = APIRouter(prefix="/api/v1/crm", tags=["crm"])


def _db():
    from app.main import db

    return db()


@router.get("/leads")
def list_crm_leads(user: auth.DeskUser = Depends(auth.get_current_user)):
    if not can_read_crm_leads(user.role):
        raise HTTPException(403, "insufficient permissions")
    with _db() as conn:
        leads = crm_leads.list_leads(conn)
        stale_hours = crm_leads.ONBOARD_STALE_HOURS
    return {
        "leads": leads,
        "total": len(leads),
        "stale_hours": stale_hours,
    }


@router.post("/leads/sync")
def sync_stale_leads(
    stale_hours: int | None = Query(default=None, ge=0, le=720),
    user: auth.DeskUser = Depends(auth.require_internal_or_user),
):
    if user.username != "worker" and not can_read_crm_leads(user.role):
        raise HTTPException(403, "insufficient permissions")
    with _db() as conn:
        result = crm_leads.promote_stale_leads(conn, stale_hours=stale_hours)
        total = crm_leads.count_leads(conn)
    result["leads_total"] = total
    return result
