"use server";

import { revalidatePath } from "next/cache";
import { requirePlatformAdmin } from "@/lib/auth/guards";
import {
  createBrigadeWithFirstAdmin,
  resetUserPassword,
} from "@/lib/admin/provisioning";
import {
  brigadeProvisionSchema,
  userResetSchema,
} from "@/lib/validation/brigade";

export type ProvisionActionResult =
  | { ok: true; tempPassword: string; geocoded: boolean }
  | { ok: false; error: string };

export type ResetActionResult =
  | { ok: true; tempPassword: string }
  | { ok: false; error: string };

/**
 * Legt eine Wehr samt erstem wehr_admin an (Geocoding + Audit in
 * provisioning.ts). Guard zuerst (default-deny, platform_admin).
 */
export async function provisionBrigade(
  input: unknown,
): Promise<ProvisionActionResult> {
  const s = await requirePlatformAdmin();
  const p = brigadeProvisionSchema.safeParse(input);
  if (!p.success) {
    return { ok: false, error: p.error.issues[0]?.message ?? "Ungültige Eingabe." };
  }
  const result = await createBrigadeWithFirstAdmin(p.data, s.user.id);
  revalidatePath("/admin/wehren");
  return {
    ok: true,
    tempPassword: result.tempPassword,
    geocoded: result.geocoded,
  };
}

/**
 * Setzt das Passwort eines lokalen Benutzers zurück (Audit `user.reset`).
 * Guard zuerst.
 */
export async function resetBrigadeUserPassword(
  input: unknown,
): Promise<ResetActionResult> {
  const s = await requirePlatformAdmin();
  const p = userResetSchema.safeParse(input);
  if (!p.success) return { ok: false, error: "Ungültige ID." };
  try {
    const { tempPassword } = await resetUserPassword(p.data.userId, s.user.id);
    revalidatePath("/admin/wehren");
    return { ok: true, tempPassword };
  } catch (e) {
    return {
      ok: false,
      error:
        e instanceof Error
          ? e.message
          : "Passwort konnte nicht zurückgesetzt werden.",
    };
  }
}
