from sqlalchemy import String, Text, ForeignKey
from sqlalchemy.orm import Mapped, mapped_column, relationship
from .base import BaseModel
from sqlalchemy.dialects.mysql import CHAR

class AuditLog(BaseModel):
    """
    Logs changes to entities (Audit Trail).
    """
    __tablename__ = 'audit_log'

    entity_type: Mapped[str] = mapped_column(String(50), nullable=False)
    entity_id: Mapped[str] = mapped_column(String(36), nullable=False)
    action: Mapped[str] = mapped_column(String(20), nullable=False) # CREATE, UPDATE, DELETE

    old_value: Mapped[str | None] = mapped_column(Text, nullable=True) # JSON representation
    new_value: Mapped[str | None] = mapped_column(Text, nullable=True) # JSON representation
    changes: Mapped[str | None] = mapped_column(Text, nullable=True) # JSON representation of diff fields

    # Explicit override of created_by to link to User model
    created_by: Mapped[str | None] = mapped_column(CHAR(36), ForeignKey('user.id'), nullable=True)
    user = relationship('User', foreign_keys=[created_by], backref='audit_logs')

    def __repr__(self):
        return f"<AuditLog {self.action} {self.entity_type} {self.entity_id}>"
