import { Module, Mutation, Action, VuexModule } from 'vuex-module-decorators'
import ManagerService from '@/widgets/messages/services/ManagerService'
import { NotifyHelper } from '@/helpers'
import { getQueryVariants } from '@/widgets/messages/helpers/search.helper'
import {
  Manager,
  ManagerCollection,
  ManagerCollectionsByGroup,
} from '@/types/Manager'

@Module({
  name: ManagerModule.storeName,
  namespaced: true,
})
export class ManagerModule extends VuexModule {
  static storeName = 'messages-ManagerModule'

  managersByGroup: ManagerCollectionsByGroup = {}
  searchQuery = ''

  get managersCollection(): ManagerCollection {
    const collections: ManagerCollection[] = Object.values(this.managersByGroup)

    return collections.reduce(
      (resultCollection, collection) => ({
        ...resultCollection,
        ...collection,
      }),
      {}
    )
  }

  get managersAsArray(): Manager[] {
    return Object.values(this.managersCollection)
  }

  get getManagerByUid() {
    return (managerUid: string): Manager => this.managersCollection[managerUid]
  }

  get managersByUids() {
    return (managerUids: string[]): Manager[] => {
      return managerUids.map(managerUid => this.getManagerByUid(managerUid))
    }
  }

  get foundManagers() {
    const queryVariants: string[] = getQueryVariants(this.searchQuery)

    return this.managersAsArray.filter(manager => {
      return queryVariants.some(
        queryVariant =>
          manager.firstName.toLowerCase().includes(queryVariant) ||
          manager.lastName.toLowerCase().includes(queryVariant)
      )
    })
  }

  @Mutation
  setManagers(managers: ManagerCollectionsByGroup) {
    this.managersByGroup = managers
  }

  @Mutation
  setSearchQuery(query: string) {
    this.searchQuery = query
  }

  @Action
  loadManagers() {
    return ManagerService.getManagers()
      .then(managers => this.setManagers(managers))
      .catch(error => {
        NotifyHelper.error('Ошибка загрузки сотрудников для сообщений')

        throw error
      })
  }
}
