# models/erp_api_call_log.py

from sqlalchemy import Column, Integer, String, Float, Boolean, DateTime, JSON
from datetime import datetime
from database import Base


class ErpApiCallLog(Base):
    """One row per outbound helixta-api -> erp-api call (services/erp_client.py),
    success or failure — lets you count/verify cross-service interactions
    from the database instead of grepping console logs.

    The three payload columns record the exchange itself: what was SENT
    (request_params for the querystring, request_body for a JSON body) and
    what came BACK (response_body). Before them the table could answer "did
    the call happen, and how slow was it" but not "what did erp-api actually
    say", which is the question that comes up whenever a card renders the
    wrong number and the console line (method/status/latency only) can't
    settle whether the fault is erp-api's payload or this app's reading of
    it.

    All three are nullable and populated best-effort — capture is switched
    by ERP_LOG_PAYLOADS, credential-shaped keys are redacted, and an
    oversized payload is stored as a marked preview (see erp_client's
    _capture_payload) — so a row always exists even when its payloads
    don't. The forwarded caller JWT lives in the Authorization header,
    which is never one of these columns.
    """

    __tablename__ = "erp_api_call_logs"

    id = Column(Integer, primary_key=True, index=True)

    method = Column(String, nullable=False)
    endpoint = Column(String, nullable=False)
    http_status = Column(Integer, nullable=True)
    latency_ms = Column(Float, nullable=True)
    success = Column(Boolean, nullable=False, default=False)
    error_code = Column(String, nullable=True)

    request_params = Column(JSON, nullable=True)
    request_body = Column(JSON, nullable=True)
    response_body = Column(JSON, nullable=True)

    company_id = Column(Integer, nullable=True)
    conversation_id = Column(String, nullable=True)

    created_at = Column(DateTime, default=datetime.utcnow)
