# @File: backend/services/whmcs_logger.py
# @Desc: Helper to persist WHMCS API activity logs without coupling the WHMCS
#        HTTP client to the DB session lifecycle. We open a short-lived session,
#        write a row, and commit. Failures here must never affect the caller.
import logging
from typing import Optional

from core.database import db_manager
from models.whmcs_api_logs import WhmcsApiLog

logger = logging.getLogger(__name__)


async def record_whmcs_call(
    *,
    action: str,
    status: str,
    user_email: Optional[str] = None,
    http_status: Optional[int] = None,
    duration_ms: Optional[int] = None,
    error: Optional[str] = None,
) -> None:
    """Persist a WhmcsApiLog entry. All exceptions are swallowed."""
    try:
        if not db_manager.async_session_maker:
            await db_manager.ensure_initialized()
        if not db_manager.async_session_maker:
            return
        async with db_manager.async_session_maker() as session:
            row = WhmcsApiLog(
                action=action[:128] if action else "unknown",
                user_email=(user_email or None),
                status=status,
                http_status=http_status,
                duration_ms=duration_ms,
                error=(error[:2000] if error else None),
            )
            session.add(row)
            await session.commit()
    except Exception:  # noqa: BLE001 - logging must never break the caller
        logger.exception("Failed to persist whmcs_api_logs row for action=%s", action)