from sqlalchemy import Column, Integer, String, ForeignKey, DateTime, Text, JSON
from sqlalchemy.orm import relationship
from datetime import datetime
from app.core.database import Base

class OperationLog(Base):
    __tablename__ = "operation_logs"

    id = Column(Integer, primary_key=True, index=True)
    app_id = Column(Integer, ForeignKey("applications.id"), nullable=True)
    operator_id = Column(Integer, ForeignKey("users.id"), nullable=False)
    
    # Action Type: MANUAL_ADD, DELETE, UPDATE, IMPORT
    action_type = Column(String(50), nullable=False, index=True)
    
    # Target info (optional, for single record ops)
    target_user_id = Column(Integer, ForeignKey("users.id"), nullable=True)
    target_mobile = Column(String(20), nullable=True) # Snapshot for search
    
    ip_address = Column(String(50), nullable=True)

    # Details (JSON for structured data like import logs, or diffs)
    details = Column(JSON, nullable=True)
    
    created_at = Column(DateTime, default=datetime.now, nullable=False)

    # Relationships
    application = relationship("Application")
    operator = relationship("User", foreign_keys=[operator_id])
    target_user = relationship("User", foreign_keys=[target_user_id])

    @property
    def operator_mobile(self):
        return self.operator.mobile if self.operator else None


