import { fetchWithAuth, getUserId } from './apiClient';

/**
 * [ADMIN ONLY] Fetches all registered users.
 */
export const getAdminUsers = async () => {
  return await fetchWithAuth('/users/admin/users');
};

/**
 * [ADMIN ONLY] Updates a user's role.
 */
export const updateUserRole = async (targetUserId, role) => {
  return await fetchWithAuth(`/users/admin/users/${targetUserId}/role`, {
    method: "PUT",
    body: { role }
  });
};

/**
 * [ADMIN ONLY] Assigns a user to a group.
 */
export const updateUserGroup = async (targetUserId, groupId) => {
  return await fetchWithAuth(`/users/admin/users/${targetUserId}/group`, {
    method: "PUT",
    body: { group_id: groupId }
  });
};

/**
 * [ADMIN ONLY] Fetches all groups.
 */
export const getAdminGroups = async () => {
  return await fetchWithAuth('/users/admin/groups');
};

/**
 * [ADMIN ONLY] Creates a new group.
 */
export const createAdminGroup = async (groupData) => {
  return await fetchWithAuth('/users/admin/groups', {
    method: "POST",
    body: groupData
  });
};

/**
 * [ADMIN ONLY] Updates a group.
 */
export const updateAdminGroup = async (groupId, groupData) => {
  return await fetchWithAuth(`/users/admin/groups/${groupId}`, {
    method: "PUT",
    body: groupData
  });
};

/**
 * [ADMIN ONLY] Deletes a group.
 */
export const deleteAdminGroup = async (groupId) => {
  return await fetchWithAuth(`/users/admin/groups/${groupId}`, {
    method: "DELETE"
  });
};

/**
 * [ADMIN ONLY] Fetches global server configuration (OIDC, Swarm).
 */
export const getAdminConfig = async () => {
  return await fetchWithAuth('/admin/config');
};

/**
 * [ADMIN ONLY] Updates OIDC configuration.
 */
export const updateAdminOIDCConfig = async (config) => {
  return await fetchWithAuth('/admin/config/oidc', {
    method: "PUT",
    body: config
  });
};

/**
 * [ADMIN ONLY] Updates Swarm configuration.
 */
export const updateAdminSwarmConfig = async (config) => {
  return await fetchWithAuth('/admin/config/swarm', {
    method: "PUT",
    body: config
  });
};

/**
 * [ADMIN ONLY] Updates basic app configuration.
 */
export const updateAdminAppConfig = async (config) => {
  return await fetchWithAuth('/admin/config/app', {
    method: "PUT",
    body: config
  });
};

/**
 * [ADMIN ONLY] Tests OIDC connectivity.
 */
export const testAdminOIDCConfig = async (config) => {
  return await fetchWithAuth('/admin/config/oidc/test', {
    method: "POST",
    body: config
  });
};

/**
 * [ADMIN ONLY] Tests Swarm endpoint connectivity.
 */
export const testAdminSwarmConfig = async (config) => {
  return await fetchWithAuth('/admin/config/swarm/test', {
    method: "POST",
    body: config
  });
};

/**
 * [ADMIN] Fetch all registered nodes.
 */
export const getAdminNodes = async () => {
  return await fetchWithAuth(`/nodes/admin`);
};

/**
 * [ADMIN] Register a new Agent Node.
 */
export const adminCreateNode = async (nodeData) => {
  return await fetchWithAuth(`/nodes/admin`, {
    method: "POST",
    body: nodeData
  });
};

/**
 * [ADMIN] Update node metadata or skill toggles.
 */
export const adminUpdateNode = async (nodeId, updateData) => {
  return await fetchWithAuth(`/nodes/admin/${nodeId}`, {
    method: "PATCH",
    body: updateData
  });
};

/**
 * [ADMIN] Deregister an Agent Node.
 */
export const adminDeleteNode = async (nodeId) => {
  return await fetchWithAuth(`/nodes/admin/${nodeId}`, {
    method: "DELETE"
  });
};

/**
 * [ADMIN] Grant a group access to a node.
 */
export const adminGrantNodeAccess = async (nodeId, grantData) => {
  return await fetchWithAuth(`/nodes/admin/${nodeId}/access`, {
    method: "POST",
    body: grantData
  });
};

/**
 * [ADMIN] Revoke a group's access to a node.
 */
export const adminRevokeNodeAccess = async (nodeId, groupId) => {
  return await fetchWithAuth(`/nodes/admin/${nodeId}/access/${groupId}`, {
    method: "DELETE"
  });
};

/**
 * [ADMIN] Download the pre-configured Agent Node bundle (ZIP).
 */
export const adminDownloadNodeBundle = async (nodeId) => {
  try {
    const url = `/nodes/admin/${nodeId}/download`;
    const response = await fetchWithAuth(url, { method: "GET", raw: true });
    const blob = await response.blob();
    const downloadUrl = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = downloadUrl;
    link.setAttribute('download', `cortex-node-${nodeId}.zip`);
    document.body.appendChild(link);
    link.click();
    link.remove();
  } catch (e) {
    throw new Error(`Failed to download node bundle: ${e.message}`);
  }
};
