import { newOperationID } from './operationKey' export type ScopeTargetType = 'directory' | 'item' export type Visibility = 'internal' | 'external' export interface ScopeRule { target_type: ScopeTargetType connection_id?: string directory_path?: string source_item_id?: string visibility: Visibility updated_by: string reason: string updated_at: string } export interface ScopeRuleTarget { target_type: ScopeTargetType connection_id: string directory_path: string source_item_id: string } export interface ScopeRuleDecision extends ScopeRuleTarget { visibility: Visibility reason: string } export interface ClearScopeRuleDecision extends ScopeRuleTarget { reason: string } export async function fetchScopeRules(connectionID: string, signal?: AbortSignal): Promise { const response = await fetch(`/api/v1/scope-rules?${new URLSearchParams({ connection_id: connectionID })}`, { headers: { Accept: 'application/json' }, signal, }) if (!response.ok) throw new Error(`加载范围规则失败(HTTP ${response.status})`) const value = (await response.json()) as { data?: unknown } if (!Array.isArray(value.data)) throw new Error('范围规则响应无效') return value.data as ScopeRule[] } async function mutateScopeRule( method: 'PUT' | 'DELETE', body: ScopeRuleDecision | ClearScopeRuleDecision ): Promise { const response = await fetch('/api/v1/scope-rules', { method, headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'Idempotency-Key': newOperationID() }, body: JSON.stringify(body), }) if (!response.ok) throw new Error(`${method === 'PUT' ? '保存' : '清除'}范围规则失败(HTTP ${response.status})`) const value = (await response.json()) as { data?: ScopeRule } if (!value.data || typeof value.data !== 'object') throw new Error('范围规则响应无效') return value.data } export function setScopeRule(decision: ScopeRuleDecision) { return mutateScopeRule('PUT', decision) } export function clearScopeRule(decision: ClearScopeRuleDecision) { return mutateScopeRule('DELETE', decision) }