import type { UnitOption } from "@/components/positions/CreatePositionModal";
import { PositionsPageClient } from "@/components/positions/PositionsPageClient";
import { daysBetweenIso } from "@/lib/format";
import { loadOrgMaps } from "@/lib/org";
import { loadOpenPositions } from "@/lib/positions";
import { currentUserId } from "@/lib/auth/session";
import { withUser } from "@/lib/db";

export default async function PositionsPage() {
  const { openPositions, orgMaps, chiefRows } = await withUser(await currentUserId(), async (tx) => {
    const [openPositions, orgMaps, chiefRows] = await Promise.all([
      loadOpenPositions(tx),
      loadOrgMaps(tx),
      // Wo es schon eine gültige Leitungsplanstelle gibt, lässt der
      // Unique-Index keine zweite zu — das gehört in den Dialog, nicht in eine
      // Fehlermeldung nach dem Absenden.
      tx.selectFrom("om_positions").select("org_unit_id").where("is_chief", "=", true).where("valid_to", "is", null).execute(),
    ]);
    return { openPositions, orgMaps, chiefRows };
  });

  const withChief = new Set(chiefRows.map((r) => r.org_unit_id));
  const units: UnitOption[] = orgMaps.unitList.map((u) => ({
    id: u.id,
    name: u.name,
    unit_type: u.unit_type,
    depth: orgMaps.depthOf.get(u.id) ?? 0,
    hasChief: withChief.has(u.id),
  }));

  const openPositionsWithDays = openPositions.map((p) => ({ ...p, daysOpen: daysBetweenIso(p.vacantSince) }));

  return <PositionsPageClient openPositions={openPositionsWithDays} units={units} />;
}
