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

      name: {
        type: DataTypes.TEXT,
      },

      tc_number: {
        type: DataTypes.TEXT,
      },

      tax_number: {
        type: DataTypes.TEXT,
      },

      insurance_number: {
        type: DataTypes.TEXT,
      },

      phone: {
        type: DataTypes.TEXT,
      },

      sector: {
        type: DataTypes.TEXT,
      },

      registration_date: {
        type: DataTypes.DATE,
      },

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

  partners.associate = (db) => {
    /// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity

    db.partners.hasMany(db.accounts, {
      as: 'accounts_partner',
      foreignKey: {
        name: 'partnerId',
      },
      constraints: false,
    });

    db.partners.hasMany(db.barter_offers, {
      as: 'barter_offers_partner',
      foreignKey: {
        name: 'partnerId',
      },
      constraints: false,
    });

    db.partners.hasMany(db.delayed_payments, {
      as: 'delayed_payments_partner',
      foreignKey: {
        name: 'partnerId',
      },
      constraints: false,
    });

    db.partners.hasMany(db.loan_applications, {
      as: 'loan_applications_partner',
      foreignKey: {
        name: 'partnerId',
      },
      constraints: false,
    });

    db.partners.hasMany(db.projects, {
      as: 'projects_partner',
      foreignKey: {
        name: 'partnerId',
      },
      constraints: false,
    });

    //end loop

    db.partners.belongsTo(db.kooperatif, {
      as: 'kooperatif',
      foreignKey: {
        name: 'kooperatifId',
      },
      constraints: false,
    });

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

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

  return partners;
};
