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,
      },

role: { type: DataTypes.ENUM, values: ["Student_Freelancer", "Client", "Admin"] }, name: { type: DataTypes.STRING }, is_verified_student: { type: DataTypes.BOOLEAN, defaultValue: false }, wallet_balance: { type: DataTypes.DECIMAL, defaultValue: 0.0 }, skills: { type: DataTypes.ARRAY(DataTypes.STRING) }, rating: { type: DataTypes.DECIMAL, defaultValue: 0.0 }, 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.service_listings, {
      as: 'service_listings_freelancer',
      foreignKey: {
          name: 'freelancerId',
      },
      constraints: false,
    });



    db.users.hasMany(db.portfolios, {
      as: 'portfolios_freelancer',
      foreignKey: {
          name: 'freelancerId',
      },
      constraints: false,
    });


    db.users.hasMany(db.jobs, {
      as: 'jobs_client',
      foreignKey: {
          name: 'clientId',
      },
      constraints: false,
    });



    db.users.hasMany(db.proposals, {
      as: 'proposals_freelancer',
      foreignKey: {
          name: 'freelancerId',
      },
      constraints: false,
    });


    db.users.hasMany(db.contracts, {
      as: 'contracts_client',
      foreignKey: {
          name: 'clientId',
      },
      constraints: false,
    });

    db.users.hasMany(db.contracts, {
      as: 'contracts_freelancer',
      foreignKey: {
          name: 'freelancerId',
      },
      constraints: false,
    });



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



    db.users.hasMany(db.messages, {
      as: 'messages_sender',
      foreignKey: {
          name: 'senderId',
      },
      constraints: false,
    });


    db.users.hasMany(db.notifications, {
      as: 'notifications_recipient',
      foreignKey: {
          name: 'recipientId',
      },
      constraints: false,
    });


    db.users.hasMany(db.payments, {
      as: 'payments_payer',
      foreignKey: {
          name: 'payerId',
      },
      constraints: false,
    });

    db.users.hasMany(db.payments, {
      as: 'payments_payee',
      foreignKey: {
          name: 'payeeId',
      },
      constraints: false,
    });


    db.users.hasMany(db.invoices, {
      as: 'invoices_billed_to',
      foreignKey: {
          name: 'billed_toId',
      },
      constraints: false,
    });

    db.users.hasMany(db.invoices, {
      as: 'invoices_billed_from',
      foreignKey: {
          name: 'billed_fromId',
      },
      constraints: false,
    });


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

    db.users.hasMany(db.reviews, {
      as: 'reviews_reviewee',
      foreignKey: {
          name: 'revieweeId',
      },
      constraints: false,
    });


    db.users.hasMany(db.disputes, {
      as: 'disputes_opened_by',
      foreignKey: {
          name: 'opened_byId',
      },
      constraints: false,
    });




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




//end loop



    db.users.belongsTo(db.roles, {
      as: 'app_role',
      foreignKey: {
        name: 'app_roleId',
      },
      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;
}

