import { and, asc, desc, eq } from "drizzle-orm";
import { db } from "@/db";
import {
  equipment,
  equipmentCategories,
  vehicles,
} from "@/db/schema";

/**
 * Lesehelfer für Geräte des Wehr-Bereichs (Workstream 7). Alle Helfer sind auf
 * eine `brigadeId` beschränkt (Scope aus Session). `vehicleId IS NULL` =
 * „im Gerätehaus".
 */

export interface EquipmentListItem {
  id: string;
  name: string;
  status: (typeof equipment.$inferSelect)["status"];
  categoryName: string;
  vehicleId: string | null;
  vehicleName: string | null;
}

/** Liste der Geräte EINER Wehr mit Kategorie- und Zuordnungsnamen. */
export async function listEquipmentForBrigade(
  brigadeId: string,
): Promise<EquipmentListItem[]> {
  return db
    .select({
      id: equipment.id,
      name: equipment.name,
      status: equipment.status,
      categoryName: equipmentCategories.name,
      vehicleId: equipment.vehicleId,
      vehicleName: vehicles.name,
    })
    .from(equipment)
    .innerJoin(
      equipmentCategories,
      eq(equipmentCategories.id, equipment.categoryId),
    )
    .leftJoin(vehicles, eq(vehicles.id, equipment.vehicleId))
    .where(eq(equipment.brigadeId, brigadeId))
    .orderBy(desc(equipment.erstelltAm));
}

/** Lädt EIN Gerät scoped auf die Wehr (sonst `null` -> notFound). */
export async function getEquipmentForBrigade(
  equipmentId: string,
  brigadeId: string,
): Promise<typeof equipment.$inferSelect | null> {
  const [e] = await db
    .select()
    .from(equipment)
    .where(
      and(eq(equipment.id, equipmentId), eq(equipment.brigadeId, brigadeId)),
    );
  return e ?? null;
}

/** Alle Geräte-Kategorien, geordnet — für die Auswahl im Formular. */
export async function listCategories(): Promise<
  { id: string; name: string }[]
> {
  return db
    .select({ id: equipmentCategories.id, name: equipmentCategories.name })
    .from(equipmentCategories)
    .orderBy(asc(equipmentCategories.reihenfolge), asc(equipmentCategories.name));
}
