import { ilike, or } from "drizzle-orm"

/**
 * Erzeugt eine OR-Suchbedingung über mehrere Spalten
 *
 * @param table - Drizzle Table Schema
 * @param columns - Array der Spaltennamen (property names im schema)
 * @param search - Suchbegriff
 */
export function buildSearchWhere(table: any, columns: string[], search: string) {
    if (!search || !columns.length) return undefined

    const term = `%${search.toLowerCase()}%`

    const parts = columns
        .map((colName) => {
            const col = table[colName]
            if (!col) return null
            return ilike(col, term)
        })
        .filter(Boolean)

    if (parts.length === 0) return undefined

    // @ts-ignore
    return or(...parts)
}
