import { Resolver, Mutation, Arg, Directive } from 'type-graphql'
import { Repository, getRepository } from 'typeorm'
import { Domain, DomainPatch } from '@things-factory/shell'
import { slugger } from '@things-factory/utils'

const debug = require('debug')('things-factory:operato-board:domain-resolver')

@Resolver(Domain)
export class DomainResolver {
  @Directive('@privilege(category: "system", privilege: "mutation", superUserGranted: true)')
  @Mutation(returns => Boolean, { description: 'To update multiple domains' })
  async updateDomains(@Arg('patches', type => [DomainPatch]) patches: DomainPatch[]): Promise<boolean> {
    const domainRepo: Repository<Domain> = getRepository(Domain)

    const _createRecords = patches.filter((patch: any) => !patch.id)
    const _updateRecords = patches.filter((patch: any) => patch.id)

    debug('update-domains')

    if (_createRecords.length > 0) {
      _createRecords.forEach(async createRecord => {
        const subdomain: string = slugger(createRecord.name)

        await domainRepo.save({ ...createRecord, subdomain })
      })
    }

    if (_updateRecords.length > 0) {
      _updateRecords.forEach(async updateRecord => {
        const domain: Domain = await domainRepo.findOne({ where: { id: updateRecord.id } })

        if (updateRecord.name) {
          updateRecord.subdomain = slugger(updateRecord.name)
        }

        await domainRepo.save({
          ...domain,
          ...updateRecord
        })
      })
    }

    return true
  }
}
