import { DataTypes } from 'sequelize';
import sequelize from '../database.js';
import bcrypt from 'bcrypt';
import { encryptData, decryptData } from '../utils/encrypt.js';

const Accident = sequelize.define('Accident', {
  memberId: {
    type: DataTypes.INTEGER,
    allowNull: false,
  },
  diaryDateId: {
    type: DataTypes.INTEGER,
    allowNull: false,
  },
  accident: {
    type: DataTypes.TEXT,
    allowNull: false,
    set(value) {
      const encryptedValue = encryptData(value);
      this.setDataValue('accident', encryptedValue);
    },
    get() {
      const encryptedValue = this.getDataValue('accident');
      return decryptData(encryptedValue);
    }
  },
  salt: {
    type: DataTypes.STRING,
    allowNull: true,
  },
}, {
  tableName: 'accident',
  underscored: true,
  timestamps: true,
  hooks: {
    beforeCreate: async (user) => {
      const salt = await bcrypt.genSalt(10);
      user.salt = salt;
    },
  }
});

export default Accident;
