const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');

module.exports = function(sequelize, DataTypes) {
  const users = sequelize.define(
    'users',
    {
      id: {
        type: DataTypes.UUID,
        defaultValue: DataTypes.UUIDV4,
        primaryKey: true,
      },

firstName: {
        type: DataTypes.TEXT,
      
      

      },

lastName: {
        type: DataTypes.TEXT,
      
      

      },

phoneNumber: {
        type: DataTypes.TEXT,
      
      

      },

email: {
        type: DataTypes.TEXT,
      
      

      },

disabled: {
        type: DataTypes.BOOLEAN,
      
        allowNull: false,
        defaultValue: false,
      
      

      },

password: {
        type: DataTypes.TEXT,
      
      

      },

emailVerified: {
        type: DataTypes.BOOLEAN,
      
        allowNull: false,
        defaultValue: false,
      
      

      },

emailVerificationToken: {
        type: DataTypes.TEXT,
      
      

      },

emailVerificationTokenExpiresAt: {
        type: DataTypes.DATE,
      
      

      },

passwordResetToken: {
        type: DataTypes.TEXT,
      
      

      },

passwordResetTokenExpiresAt: {
        type: DataTypes.DATE,
      
      

      },

provider: {
        type: DataTypes.TEXT,
      
      

      },

      importHash: {
        type: DataTypes.STRING(255),
        allowNull: true,
        unique: true,
      },
    },
    {
      timestamps: true,
      paranoid: true,
      freezeTableName: true,
    },
  );

  users.associate = (db) => {

    db.users.belongsToMany(db.permissions, {
      as: 'custom_permissions',
      foreignKey: {
        name: 'users_custom_permissionsId',
      },
      constraints: false,
      through: 'usersCustom_permissionsPermissions',
    });

    db.users.belongsToMany(db.permissions, {
      as: 'custom_permissions_filter',
      foreignKey: {
        name: 'users_custom_permissionsId',
      },
      constraints: false,
      through: 'usersCustom_permissionsPermissions',
    });


/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity








    db.users.hasMany(db.user_roles, {
      as: 'user_roles_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.audit_logs, {
      as: 'audit_logs_actor',
      foreignKey: {
          name: 'actorId',
      },
      constraints: false,
    });








    db.users.hasMany(db.inventory_transactions, {
      as: 'inventory_transactions_performed_by',
      foreignKey: {
          name: 'performed_byId',
      },
      constraints: false,
    });


    db.users.hasMany(db.stock_adjustments, {
      as: 'stock_adjustments_requested_by',
      foreignKey: {
          name: 'requested_byId',
      },
      constraints: false,
    });

    db.users.hasMany(db.stock_adjustments, {
      as: 'stock_adjustments_approved_by',
      foreignKey: {
          name: 'approved_byId',
      },
      constraints: false,
    });



    db.users.hasMany(db.interbranch_transfers, {
      as: 'interbranch_transfers_requested_by',
      foreignKey: {
          name: 'requested_byId',
      },
      constraints: false,
    });

    db.users.hasMany(db.interbranch_transfers, {
      as: 'interbranch_transfers_received_by',
      foreignKey: {
          name: 'received_byId',
      },
      constraints: false,
    });





    db.users.hasMany(db.purchase_orders, {
      as: 'purchase_orders_requested_by',
      foreignKey: {
          name: 'requested_byId',
      },
      constraints: false,
    });

    db.users.hasMany(db.purchase_orders, {
      as: 'purchase_orders_approved_by',
      foreignKey: {
          name: 'approved_byId',
      },
      constraints: false,
    });



    db.users.hasMany(db.goods_receipts, {
      as: 'goods_receipts_received_by',
      foreignKey: {
          name: 'received_byId',
      },
      constraints: false,
    });







    db.users.hasMany(db.pos_shifts, {
      as: 'pos_shifts_cashier',
      foreignKey: {
          name: 'cashierId',
      },
      constraints: false,
    });


    db.users.hasMany(db.sales, {
      as: 'sales_cashier',
      foreignKey: {
          name: 'cashierId',
      },
      constraints: false,
    });

    db.users.hasMany(db.sales, {
      as: 'sales_discount_approved_by',
      foreignKey: {
          name: 'discount_approved_byId',
      },
      constraints: false,
    });

    db.users.hasMany(db.sales, {
      as: 'sales_voided_by',
      foreignKey: {
          name: 'voided_byId',
      },
      constraints: false,
    });




    db.users.hasMany(db.refunds, {
      as: 'refunds_requested_by',
      foreignKey: {
          name: 'requested_byId',
      },
      constraints: false,
    });

    db.users.hasMany(db.refunds, {
      as: 'refunds_approved_by',
      foreignKey: {
          name: 'approved_byId',
      },
      constraints: false,
    });




    db.users.hasMany(db.checklist_runs, {
      as: 'checklist_runs_completed_by',
      foreignKey: {
          name: 'completed_byId',
      },
      constraints: false,
    });



    db.users.hasMany(db.risk_alerts, {
      as: 'risk_alerts_assigned_to',
      foreignKey: {
          name: 'assigned_toId',
      },
      constraints: false,
    });



    db.users.hasMany(db.employees, {
      as: 'employees_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });







    db.users.hasMany(db.performance_reviews, {
      as: 'performance_reviews_reviewer',
      foreignKey: {
          name: 'reviewerId',
      },
      constraints: false,
    });



    db.users.hasMany(db.journal_entries, {
      as: 'journal_entries_posted_by',
      foreignKey: {
          name: 'posted_byId',
      },
      constraints: false,
    });



    db.users.hasMany(db.expenses, {
      as: 'expenses_submitted_by',
      foreignKey: {
          name: 'submitted_byId',
      },
      constraints: false,
    });

    db.users.hasMany(db.expenses, {
      as: 'expenses_approved_by',
      foreignKey: {
          name: 'approved_byId',
      },
      constraints: false,
    });







//end loop



    db.users.belongsTo(db.roles, {
      as: 'app_role',
      foreignKey: {
        name: 'app_roleId',
      },
      constraints: false,
    });

    db.users.belongsTo(db.organizations, {
      as: 'organizations',
      foreignKey: {
        name: 'organizationsId',
      },
      constraints: false,
    });



    db.users.hasMany(db.file, {
      as: 'avatar',
      foreignKey: 'belongsToId',
      constraints: false,
      scope: {
        belongsTo: db.users.getTableName(),
        belongsToColumn: 'avatar',
      },
    });


    db.users.belongsTo(db.users, {
      as: 'createdBy',
    });

    db.users.belongsTo(db.users, {
      as: 'updatedBy',
    });
  };


    users.beforeCreate((users, options) => {
        users = trimStringFields(users);

    if (users.provider !== providers.LOCAL && Object.values(providers).indexOf(users.provider) > -1) {
        users.emailVerified = true;

        if (!users.password) {
            const password = crypto
                .randomBytes(20)
                .toString('hex');

            const hashedPassword = bcrypt.hashSync(
            password,
            config.bcrypt.saltRounds,
        );

            users.password = hashedPassword
            }
        }
    });

  users.beforeUpdate((users, options) => {
    users = trimStringFields(users);
  });
  

  return users;
};


function trimStringFields(users) {
  users.email = users.email.trim();

  users.firstName = users.firstName
    ? users.firstName.trim()
    : null;

  users.lastName = users.lastName
    ? users.lastName.trim()
    : null;

  return users;
}

