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 leads = sequelize.define(
    'leads',
    {
      id: {
        type: DataTypes.UUID,
        defaultValue: DataTypes.UUIDV4,
        primaryKey: true,
      },

title: {
        type: DataTypes.TEXT,
      
      

      },

contact_name: {
        type: DataTypes.TEXT,
      
      

      },

email: {
        type: DataTypes.TEXT,
      
      

      },

phone: {
        type: DataTypes.TEXT,
      
      

      },

source: {
        type: DataTypes.TEXT,
      
      

      },

estimated_value: {
        type: DataTypes.DECIMAL,
      
      

      },

priority: {
        type: DataTypes.ENUM,
      
      

        values: [

"low",


"medium",


"high"

        ],

      },

status: {
        type: DataTypes.ENUM,
      
      

        values: [

"open",


"won",


"lost",


"archived"

        ],

      },

created_on: {
        type: DataTypes.DATE,
      
      

      },

next_follow_up_at: {
        type: DataTypes.DATE,
      
      

      },

notes: {
        type: DataTypes.TEXT,
      
      

      },

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

  leads.associate = (db) => {

    db.leads.belongsToMany(db.tags, {
      as: 'tags',
      foreignKey: {
        name: 'leads_tagsId',
      },
      constraints: false,
      through: 'leadsTagsTags',
    });

    db.leads.belongsToMany(db.tags, {
      as: 'tags_filter',
      foreignKey: {
        name: 'leads_tagsId',
      },
      constraints: false,
      through: 'leadsTagsTags',
    });


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
























    db.leads.hasMany(db.activities, {
      as: 'activities_lead',
      foreignKey: {
          name: 'leadId',
      },
      constraints: false,
    });









//end loop



    db.leads.belongsTo(db.companies, {
      as: 'company',
      foreignKey: {
        name: 'companyId',
      },
      constraints: false,
    });

    db.leads.belongsTo(db.crm_pipelines, {
      as: 'pipeline',
      foreignKey: {
        name: 'pipelineId',
      },
      constraints: false,
    });

    db.leads.belongsTo(db.crm_stages, {
      as: 'stage',
      foreignKey: {
        name: 'stageId',
      },
      constraints: false,
    });

    db.leads.belongsTo(db.users, {
      as: 'owner',
      foreignKey: {
        name: 'ownerId',
      },
      constraints: false,
    });




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

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



  return leads;
};


