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

so_number: {
        type: DataTypes.TEXT,
      
      

      },

status: {
        type: DataTypes.ENUM,
      
      

        values: [

"draft",


"confirmed",


"allocated",


"shipped",


"invoiced",


"closed",


"cancelled"

        ],

      },

order_date: {
        type: DataTypes.DATE,
      
      

      },

requested_ship_at: {
        type: DataTypes.DATE,
      
      

      },

promised_ship_at: {
        type: DataTypes.DATE,
      
      

      },

currency: {
        type: DataTypes.TEXT,
      
      

      },

subtotal: {
        type: DataTypes.DECIMAL,
      
      

      },

tax_total: {
        type: DataTypes.DECIMAL,
      
      

      },

total: {
        type: DataTypes.DECIMAL,
      
      

      },

notes: {
        type: DataTypes.TEXT,
      
      

      },

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

  sales_orders.associate = (db) => {


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

































    db.sales_orders.hasMany(db.sales_order_lines, {
      as: 'sales_order_lines_sales_order',
      foreignKey: {
          name: 'sales_orderId',
      },
      constraints: false,
    });


    db.sales_orders.hasMany(db.shipments, {
      as: 'shipments_sales_order',
      foreignKey: {
          name: 'sales_orderId',
      },
      constraints: false,
    });











//end loop



    db.sales_orders.belongsTo(db.customers, {
      as: 'customer',
      foreignKey: {
        name: 'customerId',
      },
      constraints: false,
    });

    db.sales_orders.belongsTo(db.users, {
      as: 'sales_rep',
      foreignKey: {
        name: 'sales_repId',
      },
      constraints: false,
    });



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


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

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



  return sales_orders;
};


