from sqlalchemy import Column, Integer, String, Boolean, DateTime, ForeignKey
from sqlalchemy.sql import func
from sqlalchemy.orm import relationship
from app.database import Base

class VMAccess(Base):
    """사용자별 VM 접근 권한"""
    __tablename__ = "vm_access"
    
    id = Column(Integer, primary_key=True, index=True)
    user_id = Column(Integer, ForeignKey("users.id"), nullable=False)
    vm_id = Column(Integer, nullable=False)  # Proxmox VM ID
    node = Column(String(50), nullable=False)  # Proxmox 노드명
    vm_name = Column(String(100))
    
    # RDP 접속 정보
    rdp_username = Column(String(50))
    rdp_password = Column(String(255))  # 암호화 저장
    rdp_port = Column(Integer, default=3389)
    
    # 권한
    can_start = Column(Boolean, default=True)
    can_stop = Column(Boolean, default=True)
    can_reboot = Column(Boolean, default=True)
    can_connect = Column(Boolean, default=True)
    
    is_active = Column(Boolean, default=True)
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())
    
    # Guest Agent 없을 때 사용할 고정 IP
    static_ip = Column(String(50), nullable=True)
    
    # 관계
    user = relationship("User", back_populates="vm_accesses")
    
    def __repr__(self):
        return f"<VMAccess(user_id={self.user_id}, vm_id={self.vm_id}, node='{self.node}')>"


class SSHTunnel(Base):
    """활성 SSH 터널 세션"""
    __tablename__ = "ssh_tunnels"
    
    id = Column(Integer, primary_key=True, index=True)
    user_id = Column(Integer, ForeignKey("users.id"), nullable=False)
    vm_id = Column(Integer, nullable=False)
    
    # 터널 정보
    local_port = Column(Integer, nullable=False)  # 클라이언트가 사용할 포트
    remote_host = Column(String(50), nullable=False)  # VM IP
    remote_port = Column(Integer, nullable=False)  # VM RDP 포트
    
    # 세션 정보
    session_id = Column(String(100), unique=True, index=True)
    is_active = Column(Boolean, default=True)
    
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    closed_at = Column(DateTime(timezone=True))
    
    def __repr__(self):
        return f"<SSHTunnel(session_id='{self.session_id}', local_port={self.local_port})>"
