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

receipt_number: {
        type: DataTypes.TEXT,
      
      

      },

status: {
        type: DataTypes.ENUM,
      
      

        values: [

"draft",


"posted",


"cancelled"

        ],

      },

received_at: {
        type: DataTypes.DATE,
      
      

      },

notes: {
        type: DataTypes.TEXT,
      
      

      },

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

  receipts.associate = (db) => {

    db.receipts.belongsToMany(db.receipt_lines, {
      as: 'lines',
      foreignKey: {
        name: 'receipts_linesId',
      },
      constraints: false,
      through: 'receiptsLinesReceipt_lines',
    });

    db.receipts.belongsToMany(db.receipt_lines, {
      as: 'lines_filter',
      foreignKey: {
        name: 'receipts_linesId',
      },
      constraints: false,
      through: 'receiptsLinesReceipt_lines',
    });


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






































    db.receipts.hasMany(db.receipt_lines, {
      as: 'receipt_lines_receipt',
      foreignKey: {
          name: 'receiptId',
      },
      constraints: false,
    });



















//end loop



    db.receipts.belongsTo(db.tenants, {
      as: 'tenant',
      foreignKey: {
        name: 'tenantId',
      },
      constraints: false,
    });

    db.receipts.belongsTo(db.purchase_orders, {
      as: 'purchase_order',
      foreignKey: {
        name: 'purchase_orderId',
      },
      constraints: false,
    });

    db.receipts.belongsTo(db.locations, {
      as: 'received_into_location',
      foreignKey: {
        name: 'received_into_locationId',
      },
      constraints: false,
    });

    db.receipts.belongsTo(db.users, {
      as: 'received_by',
      foreignKey: {
        name: 'received_byId',
      },
      constraints: false,
    });

    db.receipts.belongsTo(db.organizations, {
      as: 'organizations',
      foreignKey: {
        name: 'organizationsId',
      },
      constraints: false,
    });




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

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



  return receipts;
};


