# services/pos/app/models/pos_sync.py
"""
POS Sync Log Model
Tracks synchronization operations with POS systems
"""

from sqlalchemy import Column, String, DateTime, Boolean, Integer, Text, JSON, Index, Numeric
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.sql import func
import uuid

from shared.database.base import Base


class POSSyncLog(Base):
    """
    Log of synchronization operations with POS systems
    """
    __tablename__ = "pos_sync_logs"
    
    # Primary identifiers
    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4, index=True)
    tenant_id = Column(UUID(as_uuid=True), nullable=False, index=True)
    pos_config_id = Column(UUID(as_uuid=True), nullable=False, index=True)
    
    # Sync Operation Details
    sync_type = Column(String(50), nullable=False, index=True)  # full, incremental, manual, webhook_triggered
    sync_direction = Column(String(20), nullable=False)  # inbound, outbound, bidirectional
    data_type = Column(String(50), nullable=False, index=True)  # transactions, products, customers, orders
    
    # POS Provider Information
    pos_system = Column(String(50), nullable=False, index=True)  # square, toast, lightspeed
    
    # Sync Status
    status = Column(String(50), nullable=False, default="started", index=True)  # started, in_progress, completed, failed, cancelled
    
    # Timing Information
    started_at = Column(DateTime(timezone=True), nullable=False, index=True)
    completed_at = Column(DateTime(timezone=True), nullable=True)
    duration_seconds = Column(Numeric(10, 3), nullable=True)
    
    # Date Range for Sync
    sync_from_date = Column(DateTime(timezone=True), nullable=True)
    sync_to_date = Column(DateTime(timezone=True), nullable=True)
    
    # Statistics
    records_requested = Column(Integer, default=0, nullable=False)
    records_processed = Column(Integer, default=0, nullable=False)
    records_created = Column(Integer, default=0, nullable=False)
    records_updated = Column(Integer, default=0, nullable=False)
    records_skipped = Column(Integer, default=0, nullable=False)
    records_failed = Column(Integer, default=0, nullable=False)
    
    # API Usage Statistics
    api_calls_made = Column(Integer, default=0, nullable=False)
    api_rate_limit_hits = Column(Integer, default=0, nullable=False)
    total_api_time_ms = Column(Integer, default=0, nullable=False)
    
    # Error Information
    error_message = Column(Text, nullable=True)
    error_code = Column(String(100), nullable=True)
    error_details = Column(JSON, nullable=True)
    
    # Retry Information
    retry_attempt = Column(Integer, default=0, nullable=False)
    max_retries = Column(Integer, default=3, nullable=False)
    parent_sync_id = Column(UUID(as_uuid=True), nullable=True)  # Reference to original sync for retries
    
    # Configuration Snapshot
    sync_configuration = Column(JSON, nullable=True)  # Settings used for this sync
    
    # Progress Tracking
    current_page = Column(Integer, nullable=True)
    total_pages = Column(Integer, nullable=True)
    current_batch = Column(Integer, nullable=True)
    total_batches = Column(Integer, nullable=True)
    progress_percentage = Column(Numeric(5, 2), nullable=True)
    
    # Data Quality
    validation_errors = Column(JSON, nullable=True)  # Array of validation issues
    data_quality_score = Column(Numeric(5, 2), nullable=True)  # 0-100 score
    
    # Performance Metrics
    memory_usage_mb = Column(Numeric(10, 2), nullable=True)
    cpu_usage_percentage = Column(Numeric(5, 2), nullable=True)
    network_bytes_received = Column(Integer, nullable=True)
    network_bytes_sent = Column(Integer, nullable=True)
    
    # Business Impact
    revenue_synced = Column(Numeric(12, 2), nullable=True)  # Total monetary value synced
    transactions_synced = Column(Integer, default=0, nullable=False)
    
    # Trigger Information
    triggered_by = Column(String(50), nullable=True)  # system, user, webhook, schedule
    triggered_by_user_id = Column(UUID(as_uuid=True), nullable=True)
    trigger_details = Column(JSON, nullable=True)
    
    # External References
    external_batch_id = Column(String(255), nullable=True)  # POS system's batch/job ID
    webhook_log_id = Column(UUID(as_uuid=True), nullable=True)  # If triggered by webhook
    
    # Timestamps
    created_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False)
    updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now(), nullable=False)
    
    # Metadata
    notes = Column(Text, nullable=True)
    tags = Column(JSON, nullable=True)  # Array of tags for categorization
    
    # Indexes for performance
    __table_args__ = (
        Index('idx_sync_log_tenant_started', 'tenant_id', 'started_at'),
        Index('idx_sync_log_pos_system_type', 'pos_system', 'sync_type'),
        Index('idx_sync_log_status', 'status'),
        Index('idx_sync_log_data_type', 'data_type'),
        Index('idx_sync_log_trigger', 'triggered_by'),
        Index('idx_sync_log_completed', 'completed_at'),
        Index('idx_sync_log_duration', 'duration_seconds'),
        Index('idx_sync_log_retry', 'retry_attempt'),
        Index('idx_sync_log_parent', 'parent_sync_id'),
        Index('idx_sync_log_webhook', 'webhook_log_id'),
        Index('idx_sync_log_external_batch', 'external_batch_id'),
    )
    
    def __repr__(self):
        return f"<POSSyncLog(id={self.id}, pos_system='{self.pos_system}', type='{self.sync_type}', status='{self.status}')>"