"""Global Search (spec §38): by company name, ticker, ISIN, exchange, country.

AUDIT FIX (StockLab overhaul, final engineering pass, Part A3, docs/AUDIT_SECURITY_A3.md):
rate-limited -- unauthenticated, and the `ILIKE '%q%'` leading-wildcard pattern below cannot use a
plain btree index (already a documented scan-cost concern independent of this pass,
docs/AUDIT_PERFORMANCE.md finding #4), making repeated calls a real, cheap-for-the-caller way to
generate expensive sequential scans.
"""

from fastapi import APIRouter, Depends, Query, Request
from sqlalchemy import or_, select
from sqlalchemy.orm import Session

from app.api.v1.deps import limiter
from app.core.config import get_settings
from app.core.db import get_db
from app.models import Company, Security

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

_SEARCH_RATE_LIMIT = f"{get_settings().SEARCH_RATE_LIMIT_PER_MINUTE}/minute"


@router.get("")
@limiter.limit(_SEARCH_RATE_LIMIT)
def search(request: Request, q: str = Query(..., min_length=1), limit: int = Query(20, le=50), db: Session = Depends(get_db)):
    like = f"%{q}%"
    query = (
        select(Security, Company)
        .join(Company, Security.company_id == Company.id)
        .where(or_(
            Security.ticker.ilike(like), Security.isin.ilike(like),
            Company.display_name.ilike(like), Company.legal_name.ilike(like),
        ))
        .limit(limit)
    )
    rows = db.execute(query).all()
    return [
        {"ticker": sec.ticker, "company_name": company.display_name, "isin": sec.isin,
         "country_id": company.country_id, "security_id": sec.id}
        for sec, company in rows
    ]
