module.exports = (sequelize, DataTypes) => {
  const Payslip = sequelize.define('Payslip', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    payslip_number: {
      type: DataTypes.STRING(50),
      allowNull: false,
      unique: true
    },
    company_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: {
        model: 'Company',
        key: 'id'
      }
    },
    plant_id: {
      type: DataTypes.INTEGER,
      allowNull: true,
      references: {
        model: 'Plant',
        key: 'id'
      }
    },
    payroll_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: {
        model: 'Payroll',
        key: 'id'
      }
    },
    employee_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: {
        model: 'Employee',
        key: 'id'
      }
    },
    payslip_date: {
      type: DataTypes.DATEONLY,
      allowNull: false
    },
    is_emailed: {
      type: DataTypes.BOOLEAN,
      allowNull: false,
      defaultValue: false
    },
    email_sent_date: {
      type: DataTypes.DATE,
      allowNull: true
    },
    is_downloaded: {
      type: DataTypes.BOOLEAN,
      allowNull: false,
      defaultValue: false
    },
    downloaded_date: {
      type: DataTypes.DATE,
      allowNull: true
    },
    status: {
      type: DataTypes.ENUM('GENERATED', 'SENT', 'VIEWED', 'DOWNLOADED'),
      allowNull: false,
      defaultValue: 'GENERATED'
    },
    remarks: {
      type: DataTypes.TEXT,
      allowNull: true
    }
  }, {
    tableName: 'payslip',
    indexes: [
      {
        unique: true,
        fields: ['payslip_number']
      },
      {
        fields: ['company_id']
      },
      {
        fields: ['plant_id']
      },
      {
        fields: ['payroll_id']
      },
      {
        fields: ['employee_id']
      },
      {
        fields: ['status']
      }
    ]
  });

  Payslip.associate = function(models) {
    Payslip.belongsTo(models.Company, { foreignKey: 'company_id', as: 'company' });
    Payslip.belongsTo(models.Plant, { foreignKey: 'plant_id', as: 'plant' });
    Payslip.belongsTo(models.Payroll, { foreignKey: 'payroll_id', as: 'payroll' });
    Payslip.belongsTo(models.Employee, { foreignKey: 'employee_id', as: 'employee' });
  };

  return Payslip;
};

