// src/utils/permissions.js
import axios from "axios";
const API_BASE_URL = process.env.REACT_APP_API_BASE_URL;

/**
 * Flatten moduleRoutes into { module_name, action } objects
 * @param {Array} modules - Array of moduleRoutes
 * @returns {Array} Flattened permissions
 */
export const flattenModules = (modules) => {
  const flattened = [];

  const recurse = (moduleList) => {
    moduleList.forEach((module) => {
      const name = module.name;
      const perms = module.permissions || [];
      perms.forEach((perm) => {
        flattened.push({ module_name: name, action: perm });
      });
      if (module.children) {
        recurse(module.children);
      }
    });
  };

  recurse(modules);
  return flattened;
};

/**
 * Sync module permissions with backend
 * @param {Array} moduleRoutes - The moduleRoutes array
 * @param {String} accessToken - JWT token for authentication
 * @param {String|null} tenantId - Optional tenant ID to scope permissions
 * @returns {Object} Result from backend
 */
export const syncPermissions = async (moduleRoutes, accessToken, tenantId = null) => {
  try {
    const flattenedPermissions = flattenModules(moduleRoutes);

    const payload = { permissions: flattenedPermissions };
    if (tenantId) {
      payload.tenant_id = tenantId; // for tenant-specific sync
    }
    console.log(flattenedPermissions)
    const response = await axios.post(`${API_BASE_URL}/permissions/sync/`, payload, {
      headers: {
        Authorization: `Bearer ${accessToken}`,
      },
    });

    return response.data;
  } catch (error) {
    console.error("Failed to sync permissions:", error.response?.data || error.message);
    throw error;
  }
};
