import { Injectable } from '@nestjs/common';
import {
  EventTopics,
  columnUniques,
  validateRelations,
} from 'src/core/strings/constants/interface.constants';
import { TimeGroupEntity } from '../../entities/time-group.entity';
import { TimeGroupModel } from '../../../data/models/time-group.model';
import { BaseCreateManager } from 'src/core/modules/domain/usecase/managers/base-create.manager';
import { TimeGroupCreatedEvent } from '../../entities/event/time-group-created.event';
import * as moment from 'moment';

@Injectable()
export class CreateTimeGroupManager extends BaseCreateManager<TimeGroupEntity> {
  async beforeProcess(): Promise<void> {
    const queryBuilder = this.dataService
      .getRepository()
      .createQueryBuilder(this.tableName);

    const overlapping = await queryBuilder
      .where(`${this.tableName}.start_time <= :end_time`, {
        end_time: this.data.end_time,
      })
      .andWhere(`${this.tableName}.end_time >= :start_time`, {
        start_time: this.data.start_time,
      })
      .getOne();

    if (overlapping) {
      throw new Error(
        'Rentang waktu yang dimasukkan beririsan dengan data lain.',
      );
    } else if (this.data.max_usage_time) {
      const format = 'HH:mm';
      const end_time = moment(this.data.end_time, format);
      const max_usage_time = moment(this.data.max_usage_time, format);

      if (max_usage_time.isBefore(end_time)) {
        throw new Error(
          'Waktu maksimum penggunaan harus lebih besar dari waktu selesai.',
        );
      }
      return;
    } else if (this.data.start_time && this.data.end_time) {
      const format = 'HH:mm';
      const start_time = moment(this.data.start_time, format);
      const end_time = moment(this.data.end_time, format);

      if (end_time.isBefore(start_time)) {
        throw new Error('Waktu akhir harus lebih besar dari waktu 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: TimeGroupCreatedEvent,
        data: this.data,
      },
    ];
  }

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