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

      code: {
        type: DataTypes.TEXT,
      },

      name: {
        type: DataTypes.TEXT,
      },

      period: {
        type: DataTypes.ENUM,

        values: ['monthly', 'yearly', 'both'],
      },

      price_mad: {
        type: DataTypes.DECIMAL,
      },

      limits: {
        type: DataTypes.TEXT,
      },

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

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

    db.plans.hasMany(db.subscriptions, {
      as: 'subscriptions_plan',
      foreignKey: {
        name: 'planId',
      },
      constraints: false,
    });

    db.plans.hasMany(db.tenants, {
      as: 'tenants_plan',
      foreignKey: {
        name: 'planId',
      },
      constraints: false,
    });

    //end loop

    db.plans.belongsTo(db.agences, {
      as: 'agences',
      foreignKey: {
        name: 'agencesId',
      },
      constraints: false,
    });

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

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

  return plans;
};
