import { BadRequestException } from '@nestjs/common';

/** Sin repetidos y sin vacíos. */
export function idsUnicos(ids?: string[] | null): string[] {
  return [...new Set((ids ?? []).filter(Boolean))];
}

/** Texto opcional: recortado, y vacío → null. */
export function textoONull(v?: string | null): string | null {
  const t = v?.trim();
  return t ? t : null;
}

/**
 * Exige que todos los ids pedidos estén entre los encontrados. `buscar` tiene que
 * filtrar por empresa_id (y por activo, si corresponde).
 */
export async function exigirIds(
  ids: string[],
  buscar: (ids: string[]) => Promise<Array<{ id: string }>>,
  mensaje: string,
): Promise<void> {
  if (!ids.length) return;
  const encontrados = new Set((await buscar(ids)).map((r) => r.id));
  if (ids.some((id) => !encontrados.has(id))) throw new BadRequestException(mensaje);
}

/** Las reglas devuelven una lista; el ERP responde los errores de validación como arreglo. */
export function lanzarSiHayErrores(errores: string[]): void {
  if (errores.length) throw new BadRequestException(errores);
}
