"""LAN → cloud transaction sync outbox and cloud ingest ledger."""
import uuid
from sqlalchemy import Column, String, DateTime, Text, Integer, Boolean, ForeignKey, Index, JSON
from app.models.base import BaseModel


class SyncOutboxEntry(BaseModel):
    """Pending change on local/hybrid server — pushed to cloud when online."""

    __tablename__ = "sync_outbox"

    id = Column(String, primary_key=True, default=lambda: str(uuid.uuid4()))
    entity_type = Column(String(64), nullable=False, index=True)
    entity_id = Column(String, nullable=False, index=True)
    operation = Column(String(16), default="upsert", nullable=False)  # upsert | delete
    payload = Column(JSON, nullable=False)
    status = Column(String(20), default="pending", index=True)  # pending | pushed | failed
    error_message = Column(Text, nullable=True)
    retry_count = Column(Integer, default=0)
    pushed_at = Column(DateTime, nullable=True)

    __table_args__ = (
        Index("ix_sync_outbox_status_created", "status", "created_at"),
    )


class CloudSyncLedger(BaseModel):
    """Cloud-side audit of ingested LAN events (multi-tenant hub)."""

    __tablename__ = "cloud_sync_ledger"

    id = Column(String, primary_key=True, default=lambda: str(uuid.uuid4()))
    node_id = Column(String, ForeignKey("deployment_nodes.id"), nullable=False, index=True)
    company_id = Column(String, ForeignKey("companies.id"), nullable=True, index=True)
    outbox_id = Column(String, nullable=True, index=True)
    entity_type = Column(String(64), nullable=False)
    entity_id = Column(String, nullable=False)
    operation = Column(String(16), default="upsert")
    payload = Column(JSON, nullable=True)
    apply_status = Column(String(20), default="applied")  # applied | skipped | failed
    error_message = Column(Text, nullable=True)

    __table_args__ = (
        Index("ix_cloud_sync_ledger_node_entity", "node_id", "entity_type", "entity_id"),
    )
