"""Global search — role-aware."""
from fastapi import APIRouter, Depends, Query

from deps import get_db, get_current_user
from models import MARKETING_ROLES

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


@router.get("")
async def global_search(q: str = Query(min_length=1), user: dict = Depends(get_current_user)):
    db = get_db()
    rx = {"$regex": q, "$options": "i"}
    role = user["role"]
    uid = user["id"]
    results: dict = {"projects": [], "tasks": [], "users": [], "clients": [], "departments": []}

    # PROJECTS — role-scoped
    if role == "client":
        proj_flt = {"client_id": uid, "$or": [{"name": rx}, {"description": rx}]}
    elif role == "collaborator":
        proj_flt = {"collaborator_ids": uid, "$or": [{"name": rx}, {"description": rx}]}
    else:
        proj_flt = {"$or": [{"name": rx}, {"description": rx}]}
    async for p in db.projects.find(proj_flt).limit(8):
        results["projects"].append({"id": str(p["_id"]), "name": p["name"], "status": p.get("status")})

    # TASKS — only visible projects
    if role != "client":
        if role == "collaborator":
            proj_ids = [str(p["_id"]) async for p in db.projects.find({"collaborator_ids": uid}, {"_id": 1})]
            task_flt = {"project_id": {"$in": proj_ids}, "title": rx}
        else:
            task_flt = {"title": rx}
        async for t in db.tasks.find(task_flt).limit(8):
            results["tasks"].append({"id": str(t["_id"]), "title": t["title"], "project_id": t.get("project_id"), "status": t.get("status")})

    # USERS — clients can't search users
    if role != "client":
        async for u in db.users.find({"$or": [{"name": rx}, {"email": rx}]}).limit(8):
            results["users"].append({"id": str(u["_id"]), "name": u["name"], "email": u["email"], "role": u["role"]})

    # CRM CLIENTS — marketing roles only
    if role in MARKETING_ROLES:
        async for c in db.crm_clients.find({"$or": [{"name": rx}, {"email": rx}, {"company": rx}]}).limit(8):
            results["clients"].append({"id": str(c["_id"]), "name": c["name"], "company": c.get("company", ""), "status": c.get("status")})

    # DEPARTMENTS — anyone logged in
    async for d in db.departments.find({"name": rx}).limit(5):
        results["departments"].append({"id": str(d["_id"]), "name": d["name"]})

    return results
