"""Journal append-only des opérations sensibles."""
from datetime import datetime, timezone

from ...extensions import db


class AuditLog(db.Model):
    __tablename__ = "audit_logs"

    id = db.Column(db.BigInteger, primary_key=True, autoincrement=True)
    user_id = db.Column(db.Integer, db.ForeignKey("users.id", ondelete="SET NULL"), index=True)
    username = db.Column(db.String(80), nullable=False, default="système")
    action = db.Column(db.String(16), nullable=False)
    endpoint = db.Column(db.String(160), nullable=True)
    path = db.Column(db.String(500), nullable=False)
    entity_type = db.Column(db.String(80), nullable=True, index=True)
    entity_id = db.Column(db.String(80), nullable=True, index=True)
    payload = db.Column(db.Text, nullable=True)
    status_code = db.Column(db.SmallInteger, nullable=False)
    ip_address = db.Column(db.String(64), nullable=True)
    created_at = db.Column(
        db.DateTime, nullable=False, index=True,
        default=lambda: datetime.now(timezone.utc).replace(tzinfo=None),
    )


class TemplateAuditMark(db.Model):
    """Décision administrative associée à un fichier template détecté."""
    __tablename__ = "template_audit_marks"

    id = db.Column(db.Integer, primary_key=True)
    path = db.Column(db.String(500), nullable=False, unique=True)
    status = db.Column(db.String(20), nullable=False, default="obsolete", index=True)
    notes = db.Column(db.Text, nullable=True)
    updated_by_id = db.Column(db.Integer, db.ForeignKey("users.id", ondelete="SET NULL"), nullable=True)
    updated_at = db.Column(
        db.DateTime, nullable=False,
        default=lambda: datetime.now(timezone.utc).replace(tzinfo=None),
        onupdate=lambda: datetime.now(timezone.utc).replace(tzinfo=None),
    )
