import { Module, VuexModule } from 'vuex-module-decorators'
import { Store } from 'vuex'

type ConstructorOf<M> = new (...rest: any[]) => M

let modulesCount = 0

export default function<S>(store: Store<S>, moduleName?: string) {
  return function DynamicModule<
    M extends VuexModule,
    C extends ConstructorOf<M>
  >(constructor: C): C | void {
    const name =
      moduleName ??
      (process.env.NODE_ENV === 'production'
        ? `vuexModule${modulesCount++}`
        : constructor.name)

    return Module({ dynamic: true, namespaced: true, store, name })(constructor)
  }
}
