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

invoice_number: {
        type: DataTypes.TEXT,
      
      

      },

issue_date: {
        type: DataTypes.DATE,
      
      

      },

due_date: {
        type: DataTypes.DATE,
      
      

      },

subtotal: {
        type: DataTypes.DECIMAL,
      
      

      },

discount_amount: {
        type: DataTypes.DECIMAL,
      
      

      },

tax_amount: {
        type: DataTypes.DECIMAL,
      
      

      },

total_amount: {
        type: DataTypes.DECIMAL,
      
      

      },

balance_due: {
        type: DataTypes.DECIMAL,
      
      

      },

status: {
        type: DataTypes.ENUM,
      
      

        values: [

"draft",


"issued",


"partially_paid",


"paid",


"overdue",


"void"

        ],

      },

notes: {
        type: DataTypes.TEXT,
      
      

      },

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

  invoices.associate = (db) => {


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






















    db.invoices.hasMany(db.payments, {
      as: 'payments_invoice',
      foreignKey: {
          name: 'invoiceId',
      },
      constraints: false,
    });








//end loop



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

    db.invoices.belongsTo(db.campuses, {
      as: 'campus',
      foreignKey: {
        name: 'campusId',
      },
      constraints: false,
    });

    db.invoices.belongsTo(db.students, {
      as: 'student',
      foreignKey: {
        name: 'studentId',
      },
      constraints: false,
    });

    db.invoices.belongsTo(db.fee_plans, {
      as: 'fee_plan',
      foreignKey: {
        name: 'fee_planId',
      },
      constraints: false,
    });



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


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

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



  return invoices;
};


