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

order_number: {
        type: DataTypes.TEXT,
      
      

      },

po_number: {
        type: DataTypes.TEXT,
      
      

      },

ordered_at: {
        type: DataTypes.DATE,
      
      

      },

requested_delivery_date: {
        type: DataTypes.DATE,
      
      

      },

promised_delivery_date: {
        type: DataTypes.DATE,
      
      

      },

order_status: {
        type: DataTypes.ENUM,
      
      

        values: [

"draft",


"submitted",


"approved",


"picking",


"shipped",


"delivered",


"cancelled"

        ],

      },

payment_terms: {
        type: DataTypes.ENUM,
      
      

        values: [

"net_15",


"net_30",


"net_45",


"prepaid"

        ],

      },

subtotal: {
        type: DataTypes.DECIMAL,
      
      

      },

tax_total: {
        type: DataTypes.DECIMAL,
      
      

      },

shipping_total: {
        type: DataTypes.DECIMAL,
      
      

      },

order_total: {
        type: DataTypes.DECIMAL,
      
      

      },

buyer_notes: {
        type: DataTypes.TEXT,
      
      

      },

internal_notes: {
        type: DataTypes.TEXT,
      
      

      },

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

  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.orders.hasMany(db.order_items, {
      as: 'order_items_order',
      foreignKey: {
          name: 'orderId',
      },
      constraints: false,
    });


    db.orders.hasMany(db.shipments, {
      as: 'shipments_order',
      foreignKey: {
          name: 'orderId',
      },
      constraints: false,
    });








//end loop



    db.orders.belongsTo(db.accounts, {
      as: 'account',
      foreignKey: {
        name: 'accountId',
      },
      constraints: false,
    });

    db.orders.belongsTo(db.locations, {
      as: 'location',
      foreignKey: {
        name: 'locationId',
      },
      constraints: false,
    });

    db.orders.belongsTo(db.users, {
      as: 'buyer',
      foreignKey: {
        name: 'buyerId',
      },
      constraints: false,
    });




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

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



  return orders;
};


