import { api } from './api';
import type { MyPermissions, PermissionMatrix } from '../types/permissions.types';

export const permissionsApi = {
  getMyPermissions: async (): Promise<MyPermissions> => {
    const r = await api.get('/api/permissions/me');
    return r.data.data;
  },

  getMatrix: async (): Promise<PermissionMatrix> => {
    const r = await api.get('/api/permissions/admin/matrix');
    return r.data.data;
  },

  getGroups: async (): Promise<string[]> => {
    const r = await api.get('/api/permissions/admin/groups');
    return r.data.data;
  },

  setGroupPermissions: async (group: string, permissions: string[]): Promise<void> => {
    await api.put(`/api/permissions/admin/group/${encodeURIComponent(group)}`, { permissions });
  },

  deleteGroup: async (group: string): Promise<void> => {
    await api.delete(`/api/permissions/admin/group/${encodeURIComponent(group)}`);
  },

  setBulkPermissions: async (updates: { group: string; permissions: string[] }[]): Promise<{ droppedPermissions?: string[] }> => {
    const r = await api.put('/api/permissions/admin/bulk', { updates });
    return r.data;
  },

  setMaintenanceFlag: async (featureGroup: string, active: boolean): Promise<void> => {
    await api.put(`/api/permissions/admin/maintenance/${encodeURIComponent(featureGroup)}`, { active });
  },

  getUnknownGroups: async (): Promise<string[]> => {
    const r = await api.get('/api/permissions/admin/unknown-groups');
    return r.data.data;
  },

  getDependencyConfig: async (): Promise<{
    groupHierarchy: Record<string, string[]>;
    permissionDeps: Record<string, string[]>;
  }> => {
    const r = await api.get('/api/permissions/admin/config');
    return r.data.data;
  },

  setDependencyConfig: async (config: {
    groupHierarchy?: Record<string, string[]>;
    permissionDeps?: Record<string, string[]>;
  }): Promise<void> => {
    await api.put('/api/permissions/admin/config', config);
  },
};
