'use strict';
const bcrypt = require("bcrypt");
const { Model } = require('sequelize');
const { defaultKeys, modelDefaults, actionUsers } = require('../sequelize/defaults');

module.exports = (sequelize, DataTypes) => {
  class User extends Model {
    static associate(models) {
      actionUsers(User, models, true);
      User.hasOne(models.Credintial, {
        foreignKey: 'user_id',
        sourceKey: 'user_id',
        as: 'credintial',
      });
      User.hasOne(models.Asset, {
        foreignKey: 'owner_id',
        sourceKey: 'user_id',
        constraints: false,
        scope: {
          type: 'user_image',
        },
        as: 'image',
      });
      User.belongsTo(models.Branch, {
        foreignKey: 'branch_id',
        targetKey: 'branch_id',
        as: 'branch',
      });
      User.belongsTo(models.Designation, {
        foreignKey: 'designation_id',
        targetKey: 'designation_id',
        as: 'designation',
      });
      User.hasMany(models.Collection, {
        sourceKey: "user_id",
        foreignKey: "created_by",
        as: "collectionDetails",
      });
    }
  }

  User.init({
    ...defaultKeys("user_id"),
    fullname: {
      type: DataTypes.STRING,
      allowNull: true,
    },
    role: {
      type: DataTypes.STRING,
      allowNull: true,
    },
    mobile: {
      type: DataTypes.STRING,
      allowNull: false,
      unique: true,
    },
    address: {
      type: DataTypes.STRING,
      allowNull: true,
    },
    status: {
      type: DataTypes.BOOLEAN,
      allowNull: true,
    },
  }, modelDefaults(sequelize, 'users'));

  return User;
};
