import { updateAdminUser } from "../../../db/adminUsers";

/**
 * PATCH /api/admin/users/[id] — Admin-Update für plan / banned / lyraVoiceId
 *
 * Body:
 *   {
 *     plan?: "free" | "pro" | "legend",
 *     banned?: boolean,
 *     bannedReason?: string | null,
 *     lyraVoiceId?: string | null
 *   }
 *
 * Returns: updated user-row (admin-projection).
 *
 * Auth: x-admin-secret.
 *
 * Audit: TODO(hans-mueller) — sobald audit_log table existiert, hier write
 * { actor, target_user_id, action: "admin_user_update", diff, ts }.
 * Aktuell wird die Änderung nur per console.log gespiegelt.
 */
export default defineEventHandler(async (event) => {
  const config = useRuntimeConfig();
  const secret = getHeader(event, "x-admin-secret");
  if (!config.adminSecret || secret !== config.adminSecret) {
    throw createError({ statusCode: 401, message: "Unauthorized" });
  }

  const id = getRouterParam(event, "id");
  if (!id) throw createError({ statusCode: 400, message: "User-ID fehlt" });

  const body = (await readBody(event).catch(() => ({}))) as Record<
    string,
    unknown
  >;

  const patch = {
    plan: typeof body.plan === "string" ? body.plan : undefined,
    banned: typeof body.banned === "boolean" ? body.banned : undefined,
    bannedReason:
      body.bannedReason === null
        ? null
        : typeof body.bannedReason === "string"
          ? body.bannedReason
          : undefined,
    lyraVoiceId:
      body.lyraVoiceId === null
        ? null
        : typeof body.lyraVoiceId === "string"
          ? body.lyraVoiceId
          : undefined,
  };

  const updated = await updateAdminUser(id, patch);

  // Console-audit-trail bis dedicated audit_log table verfügbar ist
  console.log(
    `[admin/users] PATCH user=${id} patch=${JSON.stringify(patch)} → plan=${updated.plan} banned=${updated.banned}`,
  );

  return updated;
});
