import { and, eq, ilike, or, type SQL } from "drizzle-orm";
import { db } from "@/db";
import { equipment } from "@/db/schema/assets";
import type { SearchHit, SearchParams } from "./types";
import { buildFilterExists } from "./query-vehicles";

/** Optionaler zusätzlicher Kategorie-Filter für die Geräte-Suche. */
export interface EquipmentSearchParams extends SearchParams {
  categoryId?: string;
}

/**
 * Serverseitige Geräte-Suche. Wie Fahrzeuge, aber OHNE Allrad-Spezialfall und
 * mit optionalem `categoryId`-Filter. Liefert UNGEORDNETE `SearchHit[]`.
 */
export async function searchEquipment(
  params: EquipmentSearchParams,
): Promise<SearchHit[]> {
  const conds: SQL[] = [];

  if (params.q && params.q.trim() !== "") {
    const pattern = `%${params.q.trim()}%`;
    const nameCond = or(ilike(equipment.name, pattern));
    if (nameCond) conds.push(nameCond);
  }

  if (params.nurEinsatzbereit) {
    conds.push(eq(equipment.status, "einsatzbereit"));
  }

  if (params.categoryId) {
    conds.push(eq(equipment.categoryId, params.categoryId));
  }

  for (const f of params.filter) {
    conds.push(buildFilterExists(f, "equipment", equipment.id));
  }

  const where = conds.length > 0 ? and(...conds) : undefined;

  const rows = await db
    .select({
      entityId: equipment.id,
      brigadeId: equipment.brigadeId,
      name: equipment.name,
      status: equipment.status,
    })
    .from(equipment)
    .where(where);

  return rows.map((r) => ({
    entityTyp: "equipment" as const,
    entityId: r.entityId,
    brigadeId: r.brigadeId,
    name: r.name,
    funkrufname: null,
    status: r.status,
  }));
}
