"""
merchant_onboarding_api_call_logs — Super Admin API-call export feature.

One row per outbound HTTP call to an external payment service, written by the
shared `helpers/log_writer.record_api_call_log()`. Two producers:
  - `service="Base CRM"` — GP Base Boarding / BaseCRM onboarding calls
    (BaseBoardingClient).
  - `service="TransIT"`  — TSYS/TransIT (TransNox) payment-provider calls
    (TSYSProvider).
The `service` column keeps the two Super Admin export buttons disjoint.
Headers/bodies are masked before insert (helpers/log_masking.py) — never store
raw Authorization headers, secrets, or other sensitive values here.
"""
from typing import Optional
from sqlalchemy import String, Integer, JSON, DateTime, ForeignKey, Text, Index
from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy.sql import func
from src.apps.base.models.base import Base
from datetime import datetime


class OnboardingApiCallLog(Base):
    __tablename__ = "onboarding_api_call_logs"

    id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True, autoincrement=True)
    merchant_id: Mapped[int] = mapped_column(Integer, ForeignKey("merchants.id"), nullable=False, index=True)
    application_id: Mapped[Optional[int]] = mapped_column(
        Integer, ForeignKey("merchant_onboarding_applications.id"), nullable=True, index=True
    )

    # "Base CRM" (onboarding) or "TransIT" (TSYS payment provider).
    service: Mapped[str] = mapped_column(String(20), nullable=False, server_default="Base CRM")
    api_name: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)

    method: Mapped[str] = mapped_column(String(10), nullable=False)
    path: Mapped[str] = mapped_column(String(255), nullable=False)
    full_url: Mapped[str] = mapped_column(String(512), nullable=False)

    request_headers: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
    request_body: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)

    response_status: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
    response_headers: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
    response_body: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)

    duration_ms: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
    correlation_id: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)

    # Text (not String(1000)) so a full traceback fits on exception.
    error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)

    created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), nullable=False)

    __table_args__ = (
        Index("ix_onboarding_api_call_logs_merchant_service", "merchant_id", "service"),
    )
