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

purchase_order_number: {
        type: DataTypes.TEXT,
      
      

      },

order_date: {
        type: DataTypes.DATE,
      
      

      },

expected_receipt_date: {
        type: DataTypes.DATE,
      
      

      },

status: {
        type: DataTypes.ENUM,
      
      

        values: [

"draft",


"sent",


"confirmed",


"partially_received",


"received",


"canceled"

        ],

      },

subtotal_ht: {
        type: DataTypes.DECIMAL,
      
      

      },

tax_total: {
        type: DataTypes.DECIMAL,
      
      

      },

total_ttc: {
        type: DataTypes.DECIMAL,
      
      

      },

notes: {
        type: DataTypes.TEXT,
      
      

      },

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

  purchase_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.purchase_orders.hasMany(db.purchase_order_items, {
      as: 'purchase_order_items_purchase_order',
      foreignKey: {
          name: 'purchase_orderId',
      },
      constraints: false,
    });


    db.purchase_orders.hasMany(db.stock_receptions, {
      as: 'stock_receptions_purchase_order',
      foreignKey: {
          name: 'purchase_orderId',
      },
      constraints: false,
    });










//end loop



    db.purchase_orders.belongsTo(db.organizations, {
      as: 'organization',
      foreignKey: {
        name: 'organizationId',
      },
      constraints: false,
    });

    db.purchase_orders.belongsTo(db.suppliers, {
      as: 'supplier',
      foreignKey: {
        name: 'supplierId',
      },
      constraints: false,
    });

    db.purchase_orders.belongsTo(db.warehouses, {
      as: 'warehouse',
      foreignKey: {
        name: 'warehouseId',
      },
      constraints: false,
    });



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


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

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



  return purchase_orders;
};


