/**
 * RBAC-based tool whitelist resolver for Claude Agent SDK.
 *
 * Resolution order:
 * 1. Start with role-based default tool set (admin > operator > viewer)
 * 2. If tenant has toolWhitelist set → intersect (only keep tools in both sets)
 * 3. If tenant has toolBlacklist set → subtract (always remove these tools)
 * 4. Return final allowedTools[] for SDK's query() call
 *
 * When toolWhitelist is empty, RBAC defaults apply.
 * toolBlacklist always takes precedence (denied regardless of role).
 */
import { Injectable } from '@nestjs/common';
import { TenantAgentConfig } from '../entities/tenant-agent-config.entity';

const ALL_SDK_TOOLS = [
  'Bash', 'Read', 'Write', 'Edit', 'Glob', 'Grep',
  'WebFetch', 'WebSearch', 'NotebookEdit', 'Task',
];

const ROLE_TOOL_MAP: Record<string, string[]> = {
  admin: [...ALL_SDK_TOOLS],
  operator: ['Bash', 'Read', 'Write', 'Edit', 'Glob', 'Grep'],
  viewer: ['Read', 'Glob', 'Grep'],
};

@Injectable()
export class AllowedToolsResolverService {
  resolve(roleType: string, tenantConfig: TenantAgentConfig | null): string[] {
    let tools = [...(ROLE_TOOL_MAP[roleType] ?? ROLE_TOOL_MAP['viewer'])];

    if (tenantConfig?.toolWhitelist?.length) {
      tools = tools.filter(t => tenantConfig.toolWhitelist.includes(t));
    }

    if (tenantConfig?.toolBlacklist?.length) {
      tools = tools.filter(t => !tenantConfig.toolBlacklist.includes(t));
    }

    return tools;
  }
}
