import { notFound } from "next/navigation";
import { requireWehrAdmin } from "@/lib/auth/guards";
import {
  getEquipmentForBrigade,
  listCategories,
} from "@/server/data/equipment";
import { listVehiclesForBrigade } from "@/server/data/vehicles";
import {
  getMerkmaleForCategory,
  getMerkmalValuesForEntity,
} from "@/server/data/merkmale";
import { getCategoryMerkmaleAction } from "@/server/actions/equipment";
import { de } from "@/lib/i18n/de";
import { EquipmentForm } from "@/components/verwaltung/EquipmentForm";
import { EquipmentControls } from "./EquipmentControls";

export default async function GeraetBearbeitenPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const s = await requireWehrAdmin();
  const { id } = await params;

  // Scoping: fremde/nicht existente Geräte -> 404.
  const item = await getEquipmentForBrigade(id, s.user.brigadeId);
  if (!item) notFound();

  const [categories, vehicles, defs, werte] = await Promise.all([
    listCategories(),
    listVehiclesForBrigade(s.user.brigadeId),
    getMerkmaleForCategory(item.categoryId),
    getMerkmalValuesForEntity("equipment", item.id),
  ]);

  return (
    <div className="space-y-6">
      <h1 className="font-display text-2xl font-semibold text-navy">
        {de.verwaltung.geraetBearbeiten}
      </h1>

      <EquipmentControls equipmentId={item.id} status={item.status} />

      <EquipmentForm
        mode="edit"
        equipmentId={item.id}
        categories={categories}
        vehicles={vehicles.map((v) => ({ id: v.id, name: v.name }))}
        initial={{
          name: item.name,
          categoryId: item.categoryId,
          vehicleId: item.vehicleId ?? "",
        }}
        definitionen={defs}
        vorhandeneWerte={werte}
        loadCategoryMerkmale={getCategoryMerkmaleAction}
      />
    </div>
  );
}
