'use strict';
const bcrypt = require("bcrypt");
const { Model } = require('sequelize');
const { defaultKeys, modelDefaults, actionUsers } = require('../sequelize/defaults');
module.exports = (sequelize, DataTypes) => {
  class Credintial extends Model {
    static associate(models) {
      Credintial.belongsTo(models.User, {
        foreignKey: 'user_id',
        targetKey: 'user_id',
        as: 'user',
      })
    }
  }

  Credintial.init({
    ...defaultKeys("credintial_id"),
    username: {
      type: DataTypes.STRING,
      unique: true,
      allowNull: true,
      validate: {
        is: new RegExp(/^[^0-9][a-zA-Z0-9_@\-\\.]{1,250}$/)
      }
    },
    password: {
      type: DataTypes.VIRTUAL,
      set(val) {
        this.setDataValue('password_hash', bcrypt.hashSync(val, 10));
      },
      validate: {
        isLongEnough(val) {
          if (val.length < 7) {
            throw new Error("Please choose a longer password");
          }
        }
      }
    },
    password_hash: {
      type: DataTypes.STRING,
      allowNull: true,
    },
  }, modelDefaults(sequelize, 'credintials', false));
  return Credintial;
};