from sqlalchemy import Column, Integer, String, DateTime, ForeignKey, Text, Enum
from sqlalchemy.sql import func
from app.database import Base
import enum

class AuditAction(str, enum.Enum):
    LOGIN = "login"
    LOGOUT = "logout"
    VM_CONNECT = "vm_connect"
    VM_DISCONNECT = "vm_disconnect"
    VM_START = "vm_start"
    VM_STOP = "vm_stop"
    VM_REBOOT = "vm_reboot"
    TUNNEL_CREATE = "tunnel_create"
    TUNNEL_CLOSE = "tunnel_close"
    USER_CREATE = "user_create"
    USER_UPDATE = "user_update"
    USER_DELETE = "user_delete"
    ACCESS_DENIED = "access_denied"

class AuditLog(Base):
    """감사 로그 - 모든 중요 작업 기록"""
    __tablename__ = "audit_logs"
    
    id = Column(Integer, primary_key=True, index=True)
    user_id = Column(Integer, ForeignKey("users.id"))
    username = Column(String(50))  # 비정규화 (삭제된 사용자 추적)
    
    action = Column(Enum(AuditAction), nullable=False, index=True)
    resource_type = Column(String(50))  # "vm", "user", "tunnel"
    resource_id = Column(String(100))  # VM ID, User ID 등
    
    ip_address = Column(String(50))
    user_agent = Column(String(255))
    
    details = Column(Text)  # JSON 형태로 추가 정보 저장
    success = Column(Integer, default=True)
    error_message = Column(Text)
    
    created_at = Column(DateTime(timezone=True), server_default=func.now(), index=True)
    
    def __repr__(self):
        return f"<AuditLog(user='{self.username}', action='{self.action}', created_at='{self.created_at}')>"
