import { DataTypes, Model, Optional, Sequelize } from 'sequelize';

export interface NotificationLogAttributes extends Optional<NotificationLogInterface, 'id'> { }

export class NotificationLog extends Model<NotificationLogInterface, NotificationLogAttributes> implements NotificationLogInterface {
    public id!: number;
    public userId!: number;
    public notificationId!: number;
    public fromUserId!: number | null;
    public replacements!: Record<string, any> | null;
    public isViewed!: boolean;
    public isRead!: boolean;
    public readonly createdAt!: Date;
    public readonly updatedAt!: Date;

    static initModel(sequelize: Sequelize): typeof NotificationLog {
        NotificationLog.init(
            {
                id: { type: DataTypes.BIGINT, autoIncrement: true, primaryKey: true, comment: "unique identifier" },
                userId: { type: DataTypes.BIGINT, allowNull: false, comment: "recipient user identifier" },
                notificationId: { type: DataTypes.BIGINT, allowNull: false, comment: "notification template identifier" },
                fromUserId: { type: DataTypes.BIGINT, allowNull: true, defaultValue: null, comment: "user who triggered the event; null means system-generated" },
                replacements: { type: DataTypes.JSON, allowNull: true, defaultValue: null, comment: "dynamic replacement values for the notification template" },
                isViewed: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: false, comment: "whether the notification has been viewed" },
                isRead: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: false, comment: "whether the notification has been read" },
            },
            {
                underscored: true,
                sequelize,
                tableName: 'notification_logs',
                timestamps: true,
                indexes: [
                    { name: 'notification-log-user-index', fields: ['user_id'] },
                    { name: 'notification-log-notification-index', fields: ['notification_id'] },
                ]
            }
        );
        return NotificationLog;
    }

    public static associate(models: any) {
        NotificationLog.belongsTo(models.User, { foreignKey: 'userId', as: 'user' });
        NotificationLog.belongsTo(models.User, { foreignKey: 'fromUserId', as: 'fromUser' });
        NotificationLog.belongsTo(models.Notification, { foreignKey: 'notificationId', as: 'notification' });
    }
}
