import { EventsHandler, IEventHandler } from '@nestjs/cqrs';
import { RecordLog } from '../entities/log.event';
import { LogService } from '../../data/services/log.service';
import { LogModel } from '../../data/models/log.model';

@EventsHandler(RecordLog)
export class RecordLogHandler implements IEventHandler<RecordLog> {
  constructor(private dataService: LogService) {}

  async handle(event: RecordLog) {
    const data = event.data;

    const queryRunner = this.dataService
      .getRepository()
      .manager.connection.createQueryRunner();

    const log = new LogModel();

    Object.assign(log, {
      data_id: data.id,
      module: data.module,
      description: data.description,
      process: data.op,
      old_data: data.old,
      data: data.data,
      created_at: new Date().getTime(),
      creator_name: data.user.name,
      creator_id: data.user.id,
    });

    await this.dataService.create(queryRunner, LogModel, log);
  }
}
