import { and, eq, isNull, SQL } from 'drizzle-orm';

export const buildWhereClause = (conditions: (SQL | undefined)[]): SQL | undefined => {
  const validConditions = conditions.filter((c): c is SQL => c !== undefined);

  if (validConditions.length === 0) {
    return undefined;
  }

  if (validConditions.length === 1) {
    return validConditions[0];
  }

  return and(...validConditions);
};

export const withoutDeleted = <T extends { deletedAt: any }>(
  table: T,
  includeDeleted = false
): SQL | undefined => {
  if (includeDeleted) {
    return undefined;
  }
  return isNull(table.deletedAt as any);
};

export const buildEqCondition = <T, K extends keyof T>(
  table: T,
  column: K,
  value: unknown
): SQL | undefined => {
  if (value === undefined || value === null) {
    return undefined;
  }
  return eq(table[column] as any, value);
};
