import { http } from "./client";
import type {
  CreateUserRequest,
  Permission,
  UpdateUserRequest,
  UserAdmin,
} from "./types";

// Admin-plane user management. Every endpoint here is admin-gated server-side
// (the `AdminUser` extractor in server/src/auth/mod.rs returns 403 for a
// non-admin). The dashboard mirrors that gate so a non-admin never reaches
// these calls, but the server is the authority.

/** GET /api/users — list every user (admin only). */
export function listUsers(signal?: AbortSignal): Promise<UserAdmin[]> {
  return http.get<UserAdmin[]>("/api/users", signal);
}

/**
 * POST /api/users — create a user (admin only). Returns the created user.
 * The plaintext password is sent in the body but NEVER echoed back in the
 * response (the server's UserInfo has no password field).
 */
export function createUser(body: CreateUserRequest): Promise<UserAdmin> {
  return http.post<UserAdmin>("/api/users", body);
}

/**
 * PUT /api/users/:id — update role / enabled / email, and optionally set a new
 * password (admin only). Permissions are NOT changed here — use setPermissions.
 */
export function updateUser(
  id: string,
  body: UpdateUserRequest,
): Promise<UserAdmin> {
  return http.put<UserAdmin>(`/api/users/${encodeURIComponent(id)}`, body);
}

/**
 * PUT /api/users/:id/permissions — replace a user's permission set (admin
 * only). Returns 200 with no body.
 */
export function setUserPermissions(
  id: string,
  permissions: (Permission | string)[],
): Promise<void> {
  return http.put<void>(`/api/users/${encodeURIComponent(id)}/permissions`, {
    permissions,
  });
}

/**
 * DELETE /api/users/:id — permanently delete a user (admin only). The server
 * refuses to delete the caller's own account (400). Returns 204.
 */
export function deleteUser(id: string): Promise<void> {
  return http.del<void>(`/api/users/${encodeURIComponent(id)}`);
}
