import { DataTypes } from 'sequelize';
import sequelize from '../database.js';
import bcrypt from 'bcrypt';

const User = sequelize.define('User', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true,
    allowNull: false
  },
  hashedId: {
    type: DataTypes.STRING(1024),
    allowNull: true,
  },
  email: {
    type: DataTypes.STRING,
    allowNull: false,
    unique: true,
  },
  password: {
    type: DataTypes.STRING,
    allowNull: false,
  },
  salt: {
    type: DataTypes.STRING,
    allowNull: true,
  },
  activationCode: {
    type: DataTypes.STRING,
    allowNull: true,
  },
  isActive: {
    type: DataTypes.BOOLEAN,
    defaultValue: false,
  },
  authCode: {
    type: DataTypes.STRING,
    allowNull: true
  },
  resetToken: {
    type: DataTypes.STRING,
    allowNull: true,
    comment: 'Token für Passwort-Reset'
  },
  resetTokenExpires: {
    type: DataTypes.DATE,
    allowNull: true,
    comment: 'Ablaufzeitpunkt des Reset-Tokens'
  }
}, {
  underscored: true,
  tableName: 'user',
  timestamps: true,
  hooks: {
    beforeCreate: async (user) => {
      const salt = await bcrypt.genSalt(10);
      user.salt = salt; 
      user.password = await bcrypt.hash(user.password, salt);
    },
    beforeUpdate: async (user) => {
      if (user.changed('password')) {
        if (!user.password.startsWith('$2b$') && !user.password.startsWith('$2a$')) {
          const salt = user.salt;
          user.password = await bcrypt.hash(user.password, salt);
        }
      }
    },
    afterCreate: async (user) => {
      user.hashedId = await bcrypt.hash(user.id.toString(), user.salt);
      await user.save(); 
    }
  },
});

User.prototype.validatePassword = function(password) {
  return bcrypt.compare(password, this.password);
};

export default User;
