"""
External Integration model for tracking external system interactions.

This model logs all interactions with external systems like SyncroMSP,
MSP Backups, Zapier webhooks, and other third-party integrations.
"""

from datetime import datetime
from typing import Optional

from sqlalchemy import CHAR, ForeignKey, Index, String, Text
from sqlalchemy.orm import Mapped, mapped_column, relationship
from sqlalchemy.sql import func

from .base import Base, UUIDMixin


class ExternalIntegration(Base, UUIDMixin):
    """
    External integration tracking for third-party system interactions.

    Logs all API calls, webhook triggers, and data exchanges with external
    systems. Useful for debugging, auditing, and understanding integration patterns.

    Attributes:
        id: Unique identifier
        session_id: Reference to the session during which integration occurred
        work_item_id: Reference to the work item this integration relates to
        integration_type: Type of integration (syncro_ticket, msp_backups, zapier_webhook)
        external_id: External system's identifier (ticket ID, asset ID, etc.)
        external_url: Direct link to the external resource
        action: What action was performed (created, updated, linked, attached)
        direction: Direction of data flow (outbound, inbound)
        request_data: JSON data that was sent to external system
        response_data: JSON data received from external system
        created_at: When the integration occurred
        created_by: User who authorized the integration
    """

    __tablename__ = "external_integrations"

    # Foreign keys
    session_id: Mapped[Optional[str]] = mapped_column(
        CHAR(36),
        ForeignKey("sessions.id", ondelete="CASCADE"),
        nullable=True,
        doc="Session during which integration occurred",
    )
    work_item_id: Mapped[Optional[str]] = mapped_column(
        CHAR(36),
        ForeignKey("work_items.id", ondelete="CASCADE"),
        nullable=True,
        doc="Work item this integration relates to",
    )

    # Integration details
    integration_type: Mapped[str] = mapped_column(
        String(100),
        nullable=False,
        doc="Type of integration (syncro_ticket, msp_backups, zapier_webhook, etc.)",
    )
    external_id: Mapped[Optional[str]] = mapped_column(
        String(255),
        nullable=True,
        doc="External system's identifier (ticket ID, asset ID, etc.)",
    )
    external_url: Mapped[Optional[str]] = mapped_column(
        String(500),
        nullable=True,
        doc="Direct link to the external resource",
    )

    # Action tracking
    action: Mapped[Optional[str]] = mapped_column(
        String(50),
        nullable=True,
        doc="Action performed (created, updated, linked, attached)",
    )
    direction: Mapped[Optional[str]] = mapped_column(
        String(20),
        nullable=True,
        doc="Direction of data flow (outbound, inbound)",
    )

    # Data
    request_data: Mapped[Optional[str]] = mapped_column(
        Text,
        nullable=True,
        doc="JSON data sent to external system",
    )
    response_data: Mapped[Optional[str]] = mapped_column(
        Text,
        nullable=True,
        doc="JSON data received from external system",
    )

    # Metadata
    created_at: Mapped[datetime] = mapped_column(
        nullable=False,
        server_default=func.now(),
        doc="When the integration occurred",
    )
    created_by: Mapped[Optional[str]] = mapped_column(
        String(255),
        nullable=True,
        doc="User who authorized the integration",
    )

    # Indexes
    __table_args__ = (
        Index("idx_ext_int_session", "session_id"),
        Index("idx_ext_int_type", "integration_type"),
        Index("idx_ext_int_external", "external_id"),
    )

    # Relationships
    # session = relationship("Session", back_populates="external_integrations")
    # work_item = relationship("WorkItem", back_populates="external_integrations")

    def __repr__(self) -> str:
        """String representation of the external integration."""
        return (
            f"<ExternalIntegration(id={self.id!r}, "
            f"type={self.integration_type!r}, "
            f"action={self.action!r}, "
            f"external_id={self.external_id!r})>"
        )
