from datetime import datetime
from src.models.database import db

class Notification(db.Model):
    __tablename__ = 'notifications'
    
    id = db.Column(db.Integer, primary_key=True)
    type = db.Column(db.String(50), nullable=False)  # BLACKLIST_ALERT, SYSTEM_ALERT, etc.
    title = db.Column(db.String(255), nullable=False)
    message = db.Column(db.Text, nullable=False)
    reference_id = db.Column(db.Integer)  # ID of related entity (e.g., recognition_id for blacklist alerts)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    
    # Relationships
    user_notifications = db.relationship('UserNotification', backref='notification', lazy=True, cascade="all, delete-orphan")
    
    def to_dict(self):
        return {
            'id': self.id,
            'type': self.type,
            'title': self.title,
            'message': self.message,
            'reference_id': self.reference_id,
            'created_at': self.created_at.isoformat() if self.created_at else None
        }


class UserNotification(db.Model):
    __tablename__ = 'user_notifications'
    
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
    notification_id = db.Column(db.Integer, db.ForeignKey('notifications.id'), nullable=False)
    is_read = db.Column(db.Boolean, default=False)
    read_at = db.Column(db.DateTime)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    
    def to_dict(self, include_notification=False):
        user_notification = {
            'id': self.id,
            'user_id': self.user_id,
            'notification_id': self.notification_id,
            'is_read': self.is_read,
            'read_at': self.read_at.isoformat() if self.read_at else None,
            'created_at': self.created_at.isoformat() if self.created_at else None
        }
        
        if include_notification and self.notification:
            user_notification['notification'] = self.notification.to_dict()
            
        return user_notification
