import { Injectable } from '@nestjs/common';
import {
  EventTopics,
  columnUniques,
  validateRelations,
} from 'src/core/strings/constants/interface.constants';
import { DataSchedulingEntity } from '../../entities/data-scheduling.entity';
import { DataSchedulingModel } from '../../../data/models/data-scheduling.model';
import { BaseCreateManager } from 'src/core/modules/domain/usecase/managers/base-create.manager';
import { DataSchedulingCreatedEvent } from '../../entities/event/data-scheduling-created.event';
import { encryptionTotal } from '../../../infrastructure/helpers';
import * as moment from 'moment';
import { STATUS } from 'src/core/strings/constants/base.constants';

@Injectable()
export class CreateDataSchedulingManager extends BaseCreateManager<DataSchedulingEntity> {
  async beforeProcess(): 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,
      })
      .getOne();

    if (this.data) {
      Object.assign(this.data, {
        indexing_key: encryptionTotal(total),
        status: STATUS.ACTIVE,
      });
    }

    // Validation date
    if (overlapping) {
      throw new Error('Tanggal yang dimasukkan beririsan dengan data lain.');
    } else if (this.data.schedule_date_from && this.data.schedule_date_to) {
      const start_time = moment(this.data.schedule_date_from);
      const end_time = moment(this.data.schedule_date_to);

      if (end_time.isBefore(start_time)) {
        throw new Error('Tanggal akhir harus lebih besar dari tanggal mulai.');
      }
      return;
    }

    return;
  }

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

  async generateConfig(): Promise<void> {
    // TODO: Implement logic here
  }

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

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

  get eventTopics(): EventTopics[] {
    return [
      {
        topic: DataSchedulingCreatedEvent,
        data: this.data,
      },
    ];
  }

  get entityTarget(): any {
    return DataSchedulingModel;
  }
}
