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

export interface PushSubscriptionAttributes {
    id: string;
    userId: string;
    endpoint: string;
    p256dh: string;
    auth: string;
    userAgent?: string;
}

export interface PushSubscriptionInstance extends Model<PushSubscriptionAttributes>, PushSubscriptionAttributes { }

export default (sequelize: Sequelize) => {
    const PushSubscription = sequelize.define<PushSubscriptionInstance>('PushSubscription', {
        id: {
            type: DataTypes.UUID,
            defaultValue: DataTypes.UUIDV4,
            primaryKey: true
        },
        userId: {
            type: DataTypes.UUID,
            allowNull: false,
            references: {
                model: 'users',
                key: 'id'
            }
        },
        endpoint: {
            type: DataTypes.TEXT,
            allowNull: false
        },
        p256dh: {
            type: DataTypes.STRING,
            allowNull: false
        },
        auth: {
            type: DataTypes.STRING,
            allowNull: false
        },
        userAgent: {
            type: DataTypes.STRING,
            allowNull: true
        }
    }, {
        tableName: 'push_subscriptions',
        timestamps: true,
        indexes: [
            { fields: ['userId'] },
            { fields: ['endpoint'], unique: true }
        ]
    });

    (PushSubscription as any).associate = (models: any) => {
        PushSubscription.belongsTo(models.User, {
            foreignKey: 'userId',
            as: 'user'
        });
    };

    return PushSubscription;
};
