"""
Audit Log Models
"""

from sqlalchemy import Column, Integer, String, Date, Time, DateTime, Text, Index, func
from sqlalchemy.dialects.postgresql import JSONB, ARRAY
from api.v1.common.base_models import TenantScopedMixin, TimestampMixin
from core.database import Base

class AuditLog(Base, TenantScopedMixin, TimestampMixin):
    __tablename__ = "audit_logs"
    __table_args__ = (
        Index('idx_audit_username_date', 'username', 'date'),
        Index('idx_audit_procedure_date', 'procedure', 'date'),
        Index('idx_audit_system_timestamp', 'system', 'timestamp'),
        Index('idx_audit_table_record', 'table_name', 'record_id'),
        {"schema": "a76"}  # Use the a76 schema for audit logs
    )
    
    # Primary Key
    spec_id = Column(Integer, primary_key=True, autoincrement=True)
    
    # Legacy Display Columns (English names as requested)
    reference = Column(String(100), nullable=False, index=True)  # Legacy: Referencia
    procedure = Column(String(100), nullable=False, index=True)  # Legacy: Procedimiento
    movement = Column(String(255), nullable=False)               # Legacy: Movimiento
    username = Column(String(100), nullable=False, index=True)   # Legacy: Usuario
    date = Column(Date, nullable=False, index=True)              # Legacy: Fecha
    time = Column(Time, nullable=False)                          # Legacy: Hora
    
    # Technical Columns
    timestamp = Column(DateTime(timezone=True), nullable=False, index=True) # Combined for queries
    system = Column(String(50), nullable=False, index=True, default="fixed_asset")
    
    # Traceability
    table_name = Column(String(100), nullable=True, index=True)
    record_id = Column(String(255), nullable=True, index=True)
    operation_type = Column(String(50), nullable=True, index=True) # CREATE, UPDATE, DELETE, LOGIN
    
    # Data Changes
    old_values = Column(JSONB, nullable=True)
    new_values = Column(JSONB, nullable=True)
    changed_fields = Column(ARRAY(String), nullable=True)
    
    # Request Context
    ip_address = Column(String(45), nullable=True)
    user_agent = Column(Text, nullable=True)
    endpoint = Column(String(500), nullable=True)
    request_method = Column(String(10), nullable=True)
    session_id = Column(String(50), nullable=True, index=True)
    execution_time_ms = Column(Integer, nullable=True)            
