const { DataTypes, QueryTypes } = require('sequelize');
const { id, name } = require('../fields');

module.exports = (sequelize) => {
  const Unit = sequelize.define(
    'Unit',
    {
      id,
      name,
      symbol: {
        type: DataTypes.STRING(64),
        allowNull: false,
        validate: {
          len: {
            args: [ 0, 64 ]
          },
          notEmpty: true,
          notNull: true
        }
      },
      group: {
        type: DataTypes.STRING(64),
        allowNull: false,
        validate: {
          len: {
            args: [ 0, 64 ]
          },
          notEmpty: true,
          notNull: true
        }
      }
    },
    {
      sequelize,
      modelName: 'Unit',
      tableName: 'units',
      createdAt: false,
      updatedAt: false,
      underscored: true,
      defaultScope: {
        include: [ { model: sequelize.models.UnitI18n } ]
      }
    }
  );

  Unit.findByLang = (lang) => {
    return sequelize.query(
      'SELECT units.id, COALESCE(unit_i18ns.name, units.name) AS name, units.symbol, units.group FROM units LEFT JOIN unit_i18ns ON unit_i18ns.unit_id = units.id AND unit_i18ns.lang = :lang',
      {
        replacements: { lang },
        type: QueryTypes.SELECT
      }
    );
  };

  Unit.findByGroup = (group, lang) => {
    return sequelize.query(
      'SELECT units.id, COALESCE(unit_i18ns.name, units.name) AS name, units.symbol FROM units LEFT JOIN unit_i18ns ON unit_i18ns.unit_id = units.id AND unit_i18ns.lang = :lang WHERE units.group = :group',
      {
        replacements: { group, lang },
        type: QueryTypes.SELECT
      }
    );
  };

  return Unit;
};
