import { HttpStatus, UnprocessableEntityException } from '@nestjs/common';
import { EMPTY_UUID } from 'src/core/strings/constants/base.constants';
import { In, Not } from 'typeorm';

export async function validateItemGate(dataService, data, id?) {
  // validate same code
  const existCode = await dataService.getOneByOptions({
    where: {
      code: data.code,
      id: Not(In([id ?? EMPTY_UUID])),
    },
  });

  if (existCode) {
    throw new UnprocessableEntityException({
      statusCode: HttpStatus.UNPROCESSABLE_ENTITY,
      message: `Gagal! Gate dengan kode ${data.code} telah ada`,
      error: 'Unprocessable Entity',
    });
  }

  // validate type item
  const existType = await dataService.getOneByOptions({
    where: {
      item_id: data.item.id,
      type: data.type,
      id: Not(In([id ?? EMPTY_UUID])),
    },
  });

  if (existType) {
    throw new UnprocessableEntityException({
      statusCode: HttpStatus.UNPROCESSABLE_ENTITY,
      message: `Gagal! Gate tipe ${data.type} dengan item ${data.item.name} telah ada`,
      error: 'Unprocessable Entity',
    });
  }
}
