import { sequelize } from '../../utils/sequelize.js';
import { DataTypes } from 'sequelize';
import { encrypt, decrypt } from '../../utils/encryption.js';

const ContactMessage = sequelize.define('contact_message', {
    email: {
        type: DataTypes.STRING,
        allowNull: false,
        set(value) {
            if (value) {
                const encryptedValue = encrypt(value);
                this.setDataValue('email', encryptedValue.toString('hex'));
            }
        },
        get() {
            const value = this.getDataValue('email');
            if (value) {
                return decrypt(Buffer.from(value, 'hex'));
            }
        }
    },
    message: {
        type: DataTypes.STRING,
        allowNull: false,
        set(value) {
            if (value) {
                const encryptedValue = encrypt(value);
                this.setDataValue('message', encryptedValue.toString('hex'));
            }
        },
        get() {
            const value = this.getDataValue('message');
            if (value) {
                return decrypt(Buffer.from(value, 'hex'));
            }
        }
    },
    name: {
        type: DataTypes.STRING,
        allowNull: false,
        set(value) {
            if (value) {
                const encryptedValue = encrypt(value);
                this.setDataValue('name', encryptedValue.toString('hex'));
            }
        },
        get() {
            const value = this.getDataValue('name');
            if (value) {
                return decrypt(Buffer.from(value, 'hex'));
            }
        }
    },
    allowDataSave: {
        type: DataTypes.BOOLEAN,
        allowNull: false
    },
    isFinished: {
        type: DataTypes.BOOLEAN,
        allowNull: false,
        defaultValue: false
    },
    // Neue Felder für die Antwort
    answer: {
        type: DataTypes.TEXT,
        allowNull: true,
        set(value) {
            if (value) {
                const encryptedValue = encrypt(value);
                this.setDataValue('answer', encryptedValue.toString('hex'));
            }
        },
        get() {
            const value = this.getDataValue('answer');
            if (value) {
                return decrypt(Buffer.from(value, 'hex'));
            }
        }
    },
    answeredAt: {
        type: DataTypes.DATE,
        allowNull: true
    },
    isAnswered: {
        type: DataTypes.BOOLEAN,
        allowNull: false,
        defaultValue: false
    }
}, {
    tableName: 'contact_message',
    timestamps: true,
    schema: 'service',
    underscored: true
});

export default ContactMessage;
