"""
Audit log model for tracking all operations
"""
from sqlalchemy import Column, String, DateTime, ForeignKey, Text
from sqlalchemy.dialects.postgresql import UUID, JSONB
from sqlalchemy.orm import relationship
from datetime import datetime
import uuid
from models import Base

class AuditLog(Base):
    """Audit log for tracking all system operations"""
    __tablename__ = "audit_logs"

    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    user_id = Column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="SET NULL"), nullable=True)
    action = Column(String(100), nullable=False, index=True)
    target = Column(String(255), nullable=True)
    outcome = Column(String(20), nullable=False)  # "success", "failure", "error"
    timestamp = Column(DateTime, default=datetime.utcnow, nullable=False, index=True)
    details = Column(JSONB, nullable=True)  # Additional context as JSON
    ip_address = Column(String(45), nullable=True)  # IPv4 or IPv6
    user_agent = Column(Text, nullable=True)

    # Relationship to user (optional - logs remain even if user deleted)
    user = relationship("User", backref="audit_logs", foreign_keys=[user_id])

    def __repr__(self):
        return f"<AuditLog(id={self.id}, action={self.action}, outcome={self.outcome}, user_id={self.user_id})>"

    def to_dict(self):
        """Convert to dictionary"""
        return {
            "id": str(self.id),
            "user_id": str(self.user_id) if self.user_id else None,
            "action": self.action,
            "target": self.target,
            "outcome": self.outcome,
            "timestamp": self.timestamp.isoformat(),
            "details": self.details,
            "ip_address": self.ip_address
        }

    @classmethod
    def log_authentication(cls, username: str, success: bool, ip_address: str = None, details: dict = None):
        """Helper to create authentication audit log"""
        return cls(
            action="auth.login",
            target=username,
            outcome="success" if success else "failure",
            details=details or {},
            ip_address=ip_address
        )

    @classmethod
    def log_crossswitch(cls, user_id: uuid.UUID, camera_id: int, monitor_id: int, success: bool, ip_address: str = None):
        """Helper to create cross-switch audit log"""
        return cls(
            user_id=user_id,
            action="crossswitch.execute",
            target=f"camera:{camera_id}->monitor:{monitor_id}",
            outcome="success" if success else "failure",
            details={
                "camera_id": camera_id,
                "monitor_id": monitor_id
            },
            ip_address=ip_address
        )

    @classmethod
    def log_clear_monitor(cls, user_id: uuid.UUID, monitor_id: int, success: bool, ip_address: str = None):
        """Helper to create clear monitor audit log"""
        return cls(
            user_id=user_id,
            action="monitor.clear",
            target=f"monitor:{monitor_id}",
            outcome="success" if success else "failure",
            details={
                "monitor_id": monitor_id
            },
            ip_address=ip_address
        )
