"""
Access audit log model for tracking data access operations.

Provides traceability for Loi 25 compliance: who accessed what, when, from where.
"""

from datetime import datetime
from src.database import db


class AccessLog(db.Model):
    """Audit trail for data access operations (view, download, edit, delete)."""

    __tablename__ = 'access_log'

    id = db.Column(db.Integer, primary_key=True)

    # Who
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=True)  # nullable for anonymous/public access
    user = db.relationship('User', backref=db.backref('access_logs', lazy='dynamic'))

    # What action
    action = db.Column(db.String(30), nullable=False)  # 'view', 'download', 'edit', 'delete', 'export', 'share'

    # What resource
    resource_type = db.Column(db.String(50), nullable=False)  # 'recording', 'audio', 'transcript', 'user', 'summary'
    resource_id = db.Column(db.Integer, nullable=True)

    # When
    timestamp = db.Column(db.DateTime, default=datetime.utcnow, nullable=False, index=True)

    # Where from
    ip_address = db.Column(db.String(45), nullable=True)
    user_agent = db.Column(db.String(500), nullable=True)

    # Result
    status = db.Column(db.String(20), default='success', nullable=False)  # 'success', 'denied', 'error'

    # Extra context (JSON)
    details = db.Column(db.JSON, nullable=True)

    def to_dict(self):
        """Convert to dictionary for API responses."""
        return {
            'id': self.id,
            'user_id': self.user_id,
            'username': self.user.username if self.user else None,
            'action': self.action,
            'resource_type': self.resource_type,
            'resource_id': self.resource_id,
            'timestamp': self.timestamp.isoformat() if self.timestamp else None,
            'ip_address': self.ip_address,
            'user_agent': self.user_agent,
            'status': self.status,
            'details': self.details,
        }

    @staticmethod
    def log_access(action, resource_type, resource_id=None, user_id=None, status='success', details=None, ip_address=None, user_agent=None):
        """Log a data access event."""
        log = AccessLog(
            user_id=user_id,
            action=action,
            resource_type=resource_type,
            resource_id=resource_id,
            status=status,
            details=details,
            ip_address=ip_address,
            user_agent=user_agent,
        )
        db.session.add(log)
        return log

    @staticmethod
    def log_view(resource_type, resource_id, user_id=None, ip_address=None, user_agent=None, details=None):
        """Log a view/read access."""
        return AccessLog.log_access('view', resource_type, resource_id, user_id=user_id, ip_address=ip_address, user_agent=user_agent, details=details)

    @staticmethod
    def log_download(resource_type, resource_id, user_id=None, ip_address=None, user_agent=None, details=None):
        """Log a download access."""
        return AccessLog.log_access('download', resource_type, resource_id, user_id=user_id, ip_address=ip_address, user_agent=user_agent, details=details)

    @staticmethod
    def log_edit(resource_type, resource_id, user_id=None, ip_address=None, user_agent=None, details=None):
        """Log an edit/modification."""
        return AccessLog.log_access('edit', resource_type, resource_id, user_id=user_id, ip_address=ip_address, user_agent=user_agent, details=details)

    @staticmethod
    def log_delete(resource_type, resource_id, user_id=None, ip_address=None, user_agent=None, details=None):
        """Log a deletion."""
        return AccessLog.log_access('delete', resource_type, resource_id, user_id=user_id, ip_address=ip_address, user_agent=user_agent, details=details)

    @staticmethod
    def log_export(resource_type, resource_id, user_id=None, ip_address=None, user_agent=None, details=None):
        """Log a data export."""
        return AccessLog.log_access('export', resource_type, resource_id, user_id=user_id, ip_address=ip_address, user_agent=user_agent, details=details)
