import apiClient from '@/lib/api-client';

/**
 * AI 工具授权管理 - API 服务层（v2.3 全量 per-user 控制）
 *
 * 对应后端：backend/src/modules/organization/ai-tools/
 * API 文档：docs/modules/organization/07-api.md  11. AI 工具授权管理 API
 */

// ==================== 类型 ====================

export type ToolCategory =
  | 'core'
  | 'fs'
  | 'runtime'
  | 'sessions'
  | 'memory'
  | 'web'
  | 'media'
  | 'automation'
  | 'browser'
  | 'productivity';

export interface AvailableTool {
  name: string;
  label: string;
  description: string;
  category: ToolCategory;
  locked: boolean;
}

export interface RoleGrantAggregated {
  roleId: string;
  roleName: string;
  roleCode: string;
  tools: string[];
  toolCount: number;
  updatedAt: string;
  updatedBy?: string;
}

export interface SetRoleGrantsResult {
  roleId: string;
  tools: string[];
  added: string[];
  removed: string[];
  toolCount: number;
}

export interface SetUserGrantsResult {
  userId: string;
  added: string[];
  removed: string[];
  reason: string;
}

export interface UserGrantsOverviewItem {
  userId: string;
  displayName: string;
  email: string;
  avatar: string | null;
  roles: Array<{ id: string; name: string; code: string }>;
  inheritedToolCount: number;
  addedCount: number;
  removedCount: number;
  effectiveToolCount: number;
}

export interface UserGrantsOverviewResponse {
  items: UserGrantsOverviewItem[];
  total: number;
  page: number;
  pageSize: number;
}

export type EffectiveToolSource =
  | { type: 'locked'; label: string }
  | { type: 'role'; roleId: string; roleName: string; grantId: string }
  | { type: 'user'; userId: string; grantId: string; reason: string | null };

export interface EffectiveToolV2 {
  toolName: string;
  category: ToolCategory;
  locked: boolean;
  sources: EffectiveToolSource[];
}

export interface UserEffectiveV2Response {
  data: EffectiveToolV2[];
  meta: {
    totalTools: number;
    lockedCount: number;
    inheritedCount: number;
    userAddedCount: number;
    userRemovedCount: number;
    userRemovedTools: string[];
  };
}

export interface ToolSubject {
  userId: string;
  userDisplayName: string;
  userEmail: string;
  orgName?: string;
  deptName?: string;
  sources: EffectiveToolSource[];
}

// ==================== v2.2 遗留类型（向后兼容） ====================

export interface AIToolGrant {
  id: string;
  roleId: string;
  toolName: string;
  createdAt: string;
  updatedAt: string;
  createdBy: string | null;
  role?: { id: string; name: string; code: string };
}

export interface AIToolGrantUser {
  id: string;
  userId: string;
  toolName: string;
  effect?: string;
  reason: string | null;
  createdAt: string;
  updatedAt: string;
  createdBy: string | null;
  user?: {
    id: string;
    username: string;
    displayName: string;
    email: string;
  };
}

// ==================== v2.3 API ====================

export async function getAvailableTools(): Promise<AvailableTool[]> {
  return apiClient.get('/ai-tools/available-tools');
}

export async function listRoleGrantsAggregated(
  search?: string,
): Promise<RoleGrantAggregated[]> {
  return apiClient.get('/ai-tools/grants/aggregated', {
    params: search ? { search } : undefined,
  });
}

export async function setRoleGrants(
  roleId: string,
  tools: string[],
): Promise<SetRoleGrantsResult> {
  return apiClient.put(`/ai-tools/grants/role/${roleId}`, { tools });
}

export async function setUserGrants(
  userId: string,
  params: { added: string[]; removed: string[]; reason: string },
): Promise<SetUserGrantsResult> {
  return apiClient.put(`/ai-tools/user-grants/${userId}`, params);
}

export async function getUserGrantsOverview(params: {
  orgId?: string;
  deptId?: string;
  roleId?: string;
  search?: string;
  hasExtra?: boolean;
  hasRevoked?: boolean;
  page?: number;
  pageSize?: number;
}): Promise<UserGrantsOverviewResponse> {
  const query: Record<string, string> = {};
  if (params.orgId) query.orgId = params.orgId;
  if (params.deptId) query.deptId = params.deptId;
  if (params.roleId) query.roleId = params.roleId;
  if (params.search) query.search = params.search;
  if (params.hasExtra) query.hasExtra = 'true';
  if (params.hasRevoked) query.hasRevoked = 'true';
  if (params.page) query.page = String(params.page);
  if (params.pageSize) query.pageSize = String(params.pageSize);
  return apiClient.get('/ai-tools/user-grants-overview', { params: query });
}

export async function getUserEffectiveToolsV2(
  userId: string,
): Promise<UserEffectiveV2Response> {
  return apiClient.get(`/ai-tools/user-effective-v2/${userId}`);
}

export async function getToolSubjects(
  toolName: string,
): Promise<ToolSubject[]> {
  return apiClient.get(
    `/ai-tools/tool-subjects/${encodeURIComponent(toolName)}`,
  );
}

// ==================== v2.2 遗留 API（内部使用） ====================

export async function listRoleGrants(roleId?: string): Promise<AIToolGrant[]> {
  return apiClient.get('/ai-tools/grants', {
    params: roleId ? { roleId } : undefined,
  });
}

export async function listUserGrants(
  userId?: string,
): Promise<AIToolGrantUser[]> {
  return apiClient.get('/ai-tools/user-grants', {
    params: userId ? { userId } : undefined,
  });
}

export async function getUserEffectiveTools(
  userId: string,
): Promise<Array<{ toolName: string; sources: EffectiveToolSource[] }>> {
  return apiClient.get(`/ai-tools/user-effective/${userId}`);
}
