import { useParsedRules } from "../../hooks/useParsedRules";
import { ReactNode } from "react";
import useRole from "../../hooks/useRole";

// Props for the WithRule component
type WithRuleProps = {
    action?: string;          // The action name, e.g., "edit"
    target: string;           // The target name, e.g., "projects"
    application?: string;     // Optional override: application/module to check rules against
    service?: string;         // Optional override: service to check rules against
    children: ReactNode;      // The React elements to render if allowed
};

/**
 * WithRule component
 * Renders its children only if the user has permission for the given action and target.
 *
 * Logic:
 * - Default behavior: allowed = true if the rule doesn't exist.
 * - Only blocks rendering if the rule exists and is explicitly false.
 *
 * By default, rules are looked up against the current route's application/service
 * (via useParams()). Pass `application`/`service` explicitly to check rules for a
 * different module regardless of the current route (e.g. a shared nav component
 * checking permissions for the module it links to, not the one it's rendered under).
 */
export const WithRule = ({ target, children, action = "edit", application, service }: WithRuleProps) => {
    const rules = useParsedRules(application, service); // Get parsed rules, optionally overridden

    const ruleKey = `can_${action}_${target}`;   // Build the rule key, e.g., "can_edit_projects"

    // Allowed if missing or true, blocked only if explicitly false
    const allowed = rules[ruleKey];

    if (!allowed) return <></>; // If not allowed, render nothing
    return <>{children}</>;     // Otherwise, render children
};

/**
 * WithRuleBoolean function
 * Returns a boolean indicating if a given action is allowed on a target.
 *
 * Logic is the same as WithRule component:
 * - true if the rule doesn't exist or is true
 * - false only if the rule exists and is explicitly false
 *
 * By default, rules are looked up against the current route's application/service.
 * Pass `application`/`service` explicitly to check a different module's rules.
 */
export const WithRuleBoolean = (
    target: string,
    action: string = "edit",
    application?: string,
    service?: string
): boolean => {
    const rules = useParsedRules(application, service);

    const ruleKey = `can_${action}_${target}`;   // Construct the rule key
    // ✅ true if missing or true, false only if explicitly false
    return rules[ruleKey] !== false;
};
