import { HttpStatus, UnprocessableEntityException } from '@nestjs/common';
import { BaseDataService } from 'src/core/modules/data/service/base-data.service';
import { columnUniques } from 'src/core/strings/constants/interface.constants';
import { TABLE_NAME } from 'src/core/strings/constants/table.constants';

export class CheckDuplicateHelper {
  constructor(
    private dataService: BaseDataService<any>,
    private tableName: TABLE_NAME,
    private duplicateColumn: columnUniques[],
    private entity: any,
    private entityId?: string,
  ) {}

  async execute() {
    for (const columnCheck of this.duplicateColumn) {
      const queryBuilder = this.dataService
        .getRepository()
        .createQueryBuilder(this.tableName);

      // process pengecekan column
      queryBuilder.where(
        `replace(trim(lower(${this.tableName}.${columnCheck.column})), '  ',' ') = :query`,
        {
          query: this.entity[columnCheck.column]
            ?.toLowerCase()
            .trim()
            .replace(/ +(?= )/g, ''),
        },
      );

      // jika ingin check specific data
      if (columnCheck.query) {
        queryBuilder.andWhere(columnCheck.query);
      }

      // jika update, akan membawa id. Maka dari itu, jangan validasi diri sendiri
      if (this.entityId) {
        queryBuilder.andWhere(`id Not In ('${this.entityId}')`);
      }

      const data_exists = await queryBuilder.getCount();
      if (data_exists > 0) {
        throw new UnprocessableEntityException({
          statusCode: HttpStatus.UNPROCESSABLE_ENTITY,
          message: `Gagal! Data dengan ${columnCheck.column} : ${
            this.entity[columnCheck.column]
          } telah ada`,
          error: 'Unprocessable Entity',
        });
      }
    }
  }
}
