import { Injectable } from '@nestjs/common';
import { BaseUpdateManager } from 'src/core/modules/domain/usecase/managers/base-update.manager';
import { DataSchedulingEntity } from '../../entities/data-scheduling.entity';
import { DataSchedulingModel } from '../../../data/models/data-scheduling.model';
import { DataSchedulingUpdatedEvent } from '../../entities/event/data-scheduling-updated.event';
import {
  EventTopics,
  columnUniques,
  validateRelations,
} from 'src/core/strings/constants/interface.constants';
import { encryptionTotal } from '../../../infrastructure/helpers';

@Injectable()
export class UpdateDataSchedulingManager extends BaseUpdateManager<DataSchedulingEntity> {
  async validateProcess(): Promise<void> {
    const total = this.data.indexing_key;

    if (total > 100) {
      throw new Error('Maksimal nilai total adalah 100.');
    }

    const queryBuilder = this.dataService
      .getRepository()
      .createQueryBuilder(this.tableName);

    const overlapping = await queryBuilder
      .where(`${this.tableName}.schedule_date_from <= :schedule_date_to`, {
        schedule_date_to: this.data.schedule_date_to,
      })
      .andWhere(`${this.tableName}.schedule_date_to >= :schedule_date_from`, {
        schedule_date_from: this.data.schedule_date_from,
      })
      .andWhere(`${this.tableName}.id != :id`, { id: this.dataId ?? null })
      .getOne();

    // Validation date
    if (overlapping) {
      throw new Error('Tanggal yang dimasukkan tidak boleh sama.');
    } else {
      //Encryption total data
      Object.assign(this.data, {
        indexing_key: encryptionTotal(total),
      });
    }

    return;
  }

  async beforeProcess(): Promise<void> {
    return;
  }

  async afterProcess(): Promise<void> {
    return;
  }

  get validateRelations(): validateRelations[] {
    return [];
  }

  get uniqueColumns(): columnUniques[] {
    return [{ column: 'name' }];
  }

  get entityTarget(): any {
    return DataSchedulingModel;
  }

  get eventTopics(): EventTopics[] {
    return [
      {
        topic: DataSchedulingUpdatedEvent,
      },
    ];
  }
}
