import { supabase } from "@/integrations/supabase/client";

/**
 * Agent 操作函数映射
 * 每个 Agent 有独立的 Edge Function
 */
export const AGENT_FUNCTIONS = {
  manager: 'admin-operations',      // 店铺经理(小管) - 通用操作、横幅、全局分析
  product: 'product-operations',    // 商品经理(小品) - 商品、分类、品牌
  marketing: 'marketing-operations', // 营销经理(小营) - 优惠券、活动、秒杀、团购
  service: 'service-operations',    // 客服经理(小服) - 订单、售后、用户服务
} as const;

export type AgentType = keyof typeof AGENT_FUNCTIONS;

/**
 * 操作类型到 Agent 的映射
 */
const OPERATION_AGENT_MAP: Record<string, AgentType> = {
  // 商品经理(小品)
  'product.query': 'product',
  'product.create': 'product',
  'product.update': 'product',
  'product.delete': 'product',
  'product.updateStock': 'product',
  'product.batchUpdateStock': 'product',
  'product.updatePrice': 'product',
  'product.batchUpdatePrice': 'product',
  'product.toggleStatus': 'product',
  'product.setRecommended': 'product',
  'product.setHot': 'product',
  'category.query': 'product',
  'category.create': 'product',
  'category.update': 'product',
  'category.delete': 'product',
  'brand.query': 'product',
  'brand.queryWithProducts': 'product',
  'brand.create': 'product',
  'brand.update': 'product',
  'brand.delete': 'product',
  'analytics.products': 'product',
  'analytics.inventory': 'product',

  // 营销经理(小营)
  'coupon.query': 'marketing',
  'coupon.create': 'marketing',
  'coupon.update': 'marketing',
  'coupon.delete': 'marketing',
  'coupon.toggleStatus': 'marketing',
  'campaign.query': 'marketing',
  'campaign.create': 'marketing',
  'campaign.update': 'marketing',
  'campaign.delete': 'marketing',
  'campaign.approve': 'marketing',
  'campaign.reject': 'marketing',
  'campaign.pause': 'marketing',
  'campaign.resume': 'marketing',
  'flashSale.query': 'marketing',
  'flashSale.create': 'marketing',
  'flashSale.update': 'marketing',
  'flashSale.delete': 'marketing',
  'flashSale.start': 'marketing',
  'flashSale.stop': 'marketing',
  'paymentGift.query': 'marketing',
  'paymentGift.create': 'marketing',
  'paymentGift.update': 'marketing',
  'paymentGift.delete': 'marketing',
  'groupBuy.query': 'marketing',
  'groupBuy.create': 'marketing',
  'groupBuy.update': 'marketing',
  'groupBuy.delete': 'marketing',
  'recharge.queryPlans': 'marketing',
  'recharge.createPlan': 'marketing',
  'recharge.updatePlan': 'marketing',
  'recharge.deletePlan': 'marketing',
  'analytics.campaigns': 'marketing',
  'analytics.marketing': 'marketing',

  // 客服经理(小服)
  'order.query': 'service',
  'order.update': 'service',
  'order.updateStatus': 'service',
  'order.addTracking': 'service',
  'order.cancel': 'service',
  'order.refund': 'service',
  'order.addNote': 'service',
  'afterSales.query': 'service',
  'afterSales.update': 'service',
  'afterSales.approve': 'service',
  'afterSales.reject': 'service',
  'afterSales.addNotes': 'service',
  'afterSales.setTracking': 'service',
  'afterSales.complete': 'service',
  'user.query': 'service',
  'user.update': 'service',
  'user.getOrders': 'service',
  'user.getAfterSales': 'service',
  'balance.query': 'service',
  'balance.queryTransactions': 'service',
  'balance.adjust': 'service',
  'analytics.orders': 'service',
  'analytics.afterSales': 'service',
  'analytics.satisfaction': 'service',

  // 店铺经理(小管)
  'banner.query': 'manager',
  'banner.create': 'manager',
  'banner.update': 'manager',
  'banner.delete': 'manager',
  'analytics.dashboard': 'manager',
  'analytics.sales': 'manager',
  'analytics.users': 'manager',
  'analytics.overview': 'manager',
  'crossDomain.getStatus': 'manager',
  'system.getConfig': 'manager',
  
  // Agent配置管理(店铺经理)
  'agent.query': 'manager',
  'agent.update': 'manager',
  'agent.setAutoExecute': 'manager',
  'agent.setMaxAmount': 'manager',
  'agent.setGoals': 'manager',
  'agent.setNotifications': 'manager',
  'agent.setApprovalTypes': 'manager',
  
  // 目标管理(店铺经理)
  'goal.query': 'manager',
  'goal.create': 'manager',
  'goal.update': 'manager',
  'goal.updateProgress': 'manager',
  'goal.delete': 'manager',
};

/**
 * 根据操作类型获取对应的 Agent
 */
export function getAgentForOperation(operation: string): AgentType {
  return OPERATION_AGENT_MAP[operation] || 'manager';
}

/**
 * 根据操作类型获取对应的 Edge Function 名称
 */
export function getFunctionForOperation(operation: string): string {
  const agent = getAgentForOperation(operation);
  return AGENT_FUNCTIONS[agent];
}

export interface OperationResponse {
  success: boolean;
  data?: any;
  message?: string;
  error?: string;
  count?: number;
  [key: string]: any;
}

/**
 * 执行 Agent 操作
 * 自动路由到正确的 Edge Function
 */
export async function executeAgentOperation(
  operation: string,
  params: Record<string, any>
): Promise<OperationResponse> {
  try {
    const functionName = getFunctionForOperation(operation);
    console.log(`[Agent-Client] ${operation} -> ${functionName}`);

    const { data, error } = await supabase.functions.invoke(functionName, {
      body: { operation, params }
    });

    if (error) {
      console.error(`[Agent-Client] 操作失败:`, error);
      return {
        success: false,
        error: error.message || '操作执行失败'
      };
    }

    return data as OperationResponse;
  } catch (error) {
    console.error(`[Agent-Client] 调用失败:`, error);
    return {
      success: false,
      error: error instanceof Error ? error.message : '未知错误'
    };
  }
}

/**
 * 直接调用指定 Agent 的操作
 */
export async function callAgent(
  agent: AgentType,
  operation: string,
  params: Record<string, any>
): Promise<OperationResponse> {
  try {
    const functionName = AGENT_FUNCTIONS[agent];
    console.log(`[Agent-Client] 直接调用 ${agent}(${functionName}): ${operation}`);

    const { data, error } = await supabase.functions.invoke(functionName, {
      body: { operation, params }
    });

    if (error) {
      console.error(`[Agent-Client] 操作失败:`, error);
      return {
        success: false,
        error: error.message || '操作执行失败'
      };
    }

    return data as OperationResponse;
  } catch (error) {
    console.error(`[Agent-Client] 调用失败:`, error);
    return {
      success: false,
      error: error instanceof Error ? error.message : '未知错误'
    };
  }
}

// ==================== 便捷操作函数 ====================

// 商品经理(小品)操作
export const productAgent = {
  query: (params: Record<string, any>) => callAgent('product', 'product.query', params),
  create: (params: Record<string, any>) => callAgent('product', 'product.create', params),
  update: (id: string, params: Record<string, any>) => callAgent('product', 'product.update', { id, ...params }),
  delete: (id: string) => callAgent('product', 'product.delete', { id }),
  updateStock: (id: string, stock_quantity: number) => callAgent('product', 'product.updateStock', { id, stock_quantity }),
  updatePrice: (id: string, price: number) => callAgent('product', 'product.updatePrice', { id, price }),
  toggleStatus: (id: string, is_active: boolean) => callAgent('product', 'product.toggleStatus', { id, is_active }),
  
  categories: {
    query: (params: Record<string, any> = {}) => callAgent('product', 'category.query', params),
    create: (params: Record<string, any>) => callAgent('product', 'category.create', params),
    update: (id: string, params: Record<string, any>) => callAgent('product', 'category.update', { id, ...params }),
    delete: (id: string) => callAgent('product', 'category.delete', { id }),
  },
  
  brands: {
    query: (params: Record<string, any> = {}) => callAgent('product', 'brand.query', params),
    create: (params: Record<string, any>) => callAgent('product', 'brand.create', params),
    update: (id: string, params: Record<string, any>) => callAgent('product', 'brand.update', { id, ...params }),
    delete: (id: string) => callAgent('product', 'brand.delete', { id }),
  },
  
  analytics: {
    products: (params: Record<string, any> = {}) => callAgent('product', 'analytics.products', params),
    inventory: (params: Record<string, any> = {}) => callAgent('product', 'analytics.inventory', params),
  }
};

// 营销经理(小营)操作
export const marketingAgent = {
  coupons: {
    query: (params: Record<string, any> = {}) => callAgent('marketing', 'coupon.query', params),
    create: (params: Record<string, any>) => callAgent('marketing', 'coupon.create', params),
    update: (id: string, params: Record<string, any>) => callAgent('marketing', 'coupon.update', { id, ...params }),
    delete: (id: string) => callAgent('marketing', 'coupon.delete', { id }),
  },
  
  campaigns: {
    query: (params: Record<string, any> = {}) => callAgent('marketing', 'campaign.query', params),
    create: (params: Record<string, any>) => callAgent('marketing', 'campaign.create', params),
    update: (id: string, params: Record<string, any>) => callAgent('marketing', 'campaign.update', { id, ...params }),
    delete: (id: string) => callAgent('marketing', 'campaign.delete', { id }),
    approve: (id: string, review_notes?: string) => callAgent('marketing', 'campaign.approve', { id, review_notes }),
    reject: (id: string, review_notes?: string) => callAgent('marketing', 'campaign.reject', { id, review_notes }),
    pause: (id: string) => callAgent('marketing', 'campaign.pause', { id }),
    resume: (id: string) => callAgent('marketing', 'campaign.resume', { id }),
  },
  
  flashSales: {
    query: (params: Record<string, any> = {}) => callAgent('marketing', 'flashSale.query', params),
    create: (params: Record<string, any>) => callAgent('marketing', 'flashSale.create', params),
    update: (id: string, params: Record<string, any>) => callAgent('marketing', 'flashSale.update', { id, ...params }),
    delete: (id: string) => callAgent('marketing', 'flashSale.delete', { id }),
    start: (id: string) => callAgent('marketing', 'flashSale.start', { id }),
    stop: (id: string) => callAgent('marketing', 'flashSale.stop', { id }),
  },
  
  groupBuys: {
    query: (params: Record<string, any> = {}) => callAgent('marketing', 'groupBuy.query', params),
    create: (params: Record<string, any>) => callAgent('marketing', 'groupBuy.create', params),
    update: (id: string, params: Record<string, any>) => callAgent('marketing', 'groupBuy.update', { id, ...params }),
    delete: (id: string) => callAgent('marketing', 'groupBuy.delete', { id }),
  },
  
  recharge: {
    queryPlans: (params: Record<string, any> = {}) => callAgent('marketing', 'recharge.queryPlans', params),
    createPlan: (params: Record<string, any>) => callAgent('marketing', 'recharge.createPlan', params),
  },
  
  analytics: {
    campaigns: (params: Record<string, any> = {}) => callAgent('marketing', 'analytics.campaigns', params),
    marketing: (params: Record<string, any> = {}) => callAgent('marketing', 'analytics.marketing', params),
  }
};

// 客服经理(小服)操作
export const serviceAgent = {
  orders: {
    query: (params: Record<string, any> = {}) => callAgent('service', 'order.query', params),
    update: (id: string, params: Record<string, any>) => callAgent('service', 'order.update', { id, ...params }),
    addTracking: (id: string, tracking_number: string) => callAgent('service', 'order.addTracking', { id, tracking_number }),
    cancel: (id: string, reason?: string) => callAgent('service', 'order.cancel', { id, reason }),
    refund: (id: string, amount: number, reason?: string) => callAgent('service', 'order.refund', { id, amount, reason }),
  },
  
  afterSales: {
    query: (params: Record<string, any> = {}) => callAgent('service', 'afterSales.query', params),
    approve: (id: string, refund_amount?: number, admin_notes?: string) => callAgent('service', 'afterSales.approve', { id, refund_amount, admin_notes }),
    reject: (id: string, reason: string) => callAgent('service', 'afterSales.reject', { id, reason }),
    complete: (id: string, admin_notes?: string) => callAgent('service', 'afterSales.complete', { id, admin_notes }),
  },
  
  users: {
    query: (params: Record<string, any> = {}) => callAgent('service', 'user.query', params),
    update: (id: string, params: Record<string, any>) => callAgent('service', 'user.update', { id, ...params }),
    getOrders: (userId: string) => callAgent('service', 'user.getOrders', { userId }),
    getAfterSales: (userId: string) => callAgent('service', 'user.getAfterSales', { userId }),
  },
  
  balance: {
    query: (params: Record<string, any> = {}) => callAgent('service', 'balance.query', params),
    adjust: (user_id: string, amount: number, description?: string) => callAgent('service', 'balance.adjust', { user_id, amount, description }),
  },
  
  analytics: {
    orders: (params: Record<string, any> = {}) => callAgent('service', 'analytics.orders', params),
    afterSales: (params: Record<string, any> = {}) => callAgent('service', 'analytics.afterSales', params),
    satisfaction: (params: Record<string, any> = {}) => callAgent('service', 'analytics.satisfaction', params),
  }
};

// 店铺经理(小管)操作
export const managerAgent = {
  banners: {
    query: (params: Record<string, any> = {}) => callAgent('manager', 'banner.query', params),
    create: (params: Record<string, any>) => callAgent('manager', 'banner.create', params),
    update: (id: string, params: Record<string, any>) => callAgent('manager', 'banner.update', { id, ...params }),
    delete: (id: string) => callAgent('manager', 'banner.delete', { id }),
  },
  
  goals: {
    query: (params: Record<string, any> = {}) => callAgent('manager', 'goal.query', params),
    create: (params: Record<string, any>) => callAgent('manager', 'goal.create', params),
    update: (id: string, params: Record<string, any>) => callAgent('manager', 'goal.update', { id, ...params }),
    updateProgress: (id: string, currentValue: number) => callAgent('manager', 'goal.updateProgress', { id, currentValue }),
    delete: (id: string) => callAgent('manager', 'goal.delete', { id }),
  },
  
  analytics: {
    dashboard: (params: Record<string, any> = {}) => callAgent('manager', 'analytics.dashboard', params),
    sales: (params: Record<string, any> = {}) => callAgent('manager', 'analytics.sales', params),
    users: (params: Record<string, any> = {}) => callAgent('manager', 'analytics.users', params),
    overview: () => callAgent('manager', 'analytics.overview', {}),
  },
  
  crossDomain: {
    getStatus: () => callAgent('manager', 'crossDomain.getStatus', {}),
  },
  
  system: {
    getConfig: () => callAgent('manager', 'system.getConfig', {}),
  }
};

// 兼容旧版 API
export const executeAdminOperation = executeAgentOperation;

// 旧版兼容导出
export const productOperations = productAgent;
export const orderOperations = serviceAgent.orders;
export const userOperations = serviceAgent.users;
export const afterSalesOperations = serviceAgent.afterSales;
export const categoryOperations = productAgent.categories;
export const brandOperations = productAgent.brands;
export const bannerOperations = managerAgent.banners;
export const analyticsOperations = managerAgent.analytics;
