import {CommandHandler, EventBus, ICommandHandler} from "@nestjs/cqrs";
import {Promise} from "mongoose";
import {GuestsService} from "../../guests.service";
import {Logger} from "@nestjs/common";
import {SetGuestPropertyCommand} from "../set-guest-property.command";
import {UserPropertyChangedEvent} from "../../event-handlers/user-property-changed.event";

@CommandHandler(SetGuestPropertyCommand)
export class SetGuestPropertyCommandHandler implements ICommandHandler<SetGuestPropertyCommand> {
  private readonly logger = new Logger(SetGuestPropertyCommandHandler.name);
  constructor(private guestService: GuestsService, private eventBus: EventBus) {
  }
  async execute(command: SetGuestPropertyCommand): Promise<any> {
    const user = await this.guestService.findById(command.user);
    this.logger.verbose('enter');
    if(!user) {
      throw new Error(`Can't find specified user: ${command.user}`);
    }
    this.logger.verbose(`User properties: ${user.properties}`);
    let resultValue = command.propertyValue;
    this.logger.verbose(`Allow increment ${command.allowIncrement}`);
    if(command.allowIncrement) {
      const currentValue = user.get(`properties.${command.propertyName}`)
      const newProp = (parseInt(currentValue) + parseInt(command.propertyValue)).toString();
      this.logger.verbose(`Incremented to ${newProp}`);
      if(!isNaN(parseInt(newProp))) {
        resultValue  = newProp;
      }
    }
    user.set(`properties.${command.propertyName}`, resultValue);
    this.logger.verbose(`Set property ${command.propertyName} for ${command.user} to ${resultValue}`);
    this.eventBus.publish(new UserPropertyChangedEvent(user.telegramId, command.propertyName, command.propertyValue))
    await user.save();
  }

}