import api from "../axios";

export interface PermissionNode {
  node: string;
  description: string;
  usedIn: string[];
  dependencies?: string[];
  /**
   * When present, lists field-level permission nodes gated by this
   * permission via `processObjectValuePerms`. Each entry is a full
   * permission node string (e.g. `obj.company.id`).
   */
  fieldLevelPermissions?: string[];
}

export interface PermissionCategory {
  name: string;
  description: string;
  permissions: PermissionNode[];
  subCategories?: Record<string, PermissionCategory>;
}

export interface PermissionsCategorized {
  [category: string]: PermissionCategory;
}

export const permission = {
  async fetchCategorized(accessToken: string) {
    const response = await api.get("/v1/permissions", {
      headers: {
        Authorization: `Bearer ${accessToken}`,
      },
    });
    return response.data;
  },

  async fetchFlat(accessToken: string) {
    const response = await api.get("/v1/permissions/nodes", {
      headers: {
        Authorization: `Bearer ${accessToken}`,
      },
    });
    return response.data;
  },

  async fetchByCategory(accessToken: string, category: string) {
    const response = await api.get(`/v1/permissions/${category}`, {
      headers: {
        Authorization: `Bearer ${accessToken}`,
      },
    });
    return response.data;
  },
};
