module.exports = (sequelize, DataTypes) => {
  const NumberSequence = sequelize.define('NumberSequence', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    company_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: { model: 'Company', key: 'id' }
    },
    module_name: {
      type: DataTypes.STRING(50),
      allowNull: false,
      comment: 'Module: PRODUCTION_ORDER, MATERIAL_REQUEST, PURCHASE_ORDER, etc.'
    },
    fiscal_year_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: { model: 'FiscalYear', key: 'id' }
    },
    current_sequence: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 0,
      comment: 'Last used sequence for this company+module+FY'
    }
  }, {
    tableName: 'number_sequence',
    timestamps: true,
    underscored: true,
    indexes: [
      {
        unique: true,
        fields: ['company_id', 'module_name', 'fiscal_year_id'],
        name: 'unique_company_module_fiscal_year'
      },
      { fields: ['company_id', 'module_name'], name: 'idx_number_sequence_company_module' }
    ]
  });

  NumberSequence.associate = function(models) {
    NumberSequence.belongsTo(models.Company, { foreignKey: 'company_id', as: 'company' });
    NumberSequence.belongsTo(models.FiscalYear, { foreignKey: 'fiscal_year_id', as: 'fiscalYear' });
  };

  return NumberSequence;
};
