import { sequelize } from '../../utils/sequelize.js';
import { DataTypes } from 'sequelize';
import User from './user.js';
import UserParamType from '../type/user_param.js';
import { encrypt, decrypt } from '../../utils/encryption.js';

const UserParam = sequelize.define('user_param', {
    userId: {
        type: DataTypes.INTEGER,
        allowNull: false
    },
    paramTypeId: {
        type: DataTypes.INTEGER,
        allowNull: false
    },
    value: {
        type: DataTypes.STRING,
        allowNull: false,
        set(value) {
            if (value) {
                try {
                    const encrypted = encrypt(value.toString()); 
                    this.setDataValue('value', encrypted); 
                } catch (error) {
                    console.error('.... Error encrypting param value:', error);
                    this.setDataValue('value', ''); 
                }
            }
        },
        get() {
            try {
                const value = this.getDataValue('value'); 
                return decrypt(value); 
            } catch (error) {
                console.error('.... Error decrypting param value:', error);
                return '';
            }
        },
    },
}, {
    tableName: 'user_param',
    schema: 'community',
    underscored: true,
    indexes: [
        {
            unique: true,
            fields: ['user_id', 'param_type_id'], 
        }
    ],
});

export default UserParam;
