/**
 * [FE-DS-012] 批量操作数据源
 * 提供批量操作的统一数据接口
 * AI注意: 所有批量操作数据必须通过此数据源
 */

import { http } from './http';

export interface BatchOperationRecord {
  id: string;
  tenantId: string;
  shopId: string;
  operatorId: string;
  operatorName: string;
  operationType: string;
  status: string;
  targetType: 'PRODUCT' | 'AD_CAMPAIGN' | 'AD_CREATIVE';
  targetIds: string[];
  totalCount: number;
  successCount: number;
  failedCount: number;
  aiConfidence?: number;
  aiReason?: string;
  riskLevel?: 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL';
  subscriptionLevel?: 'FREE' | 'BASIC' | 'PROFESSIONAL' | 'ENTERPRISE';
  aiAutoExecuted: boolean;
  createdAt: string;
  updatedAt: string;
}

export interface BatchOperationQuery {
  tenantId: string;
  shopId?: string;
  operationType?: string;
  status?: string;
  startDate?: string;
  endDate?: string;
  page?: number;
  pageSize?: number;
}

export interface BatchOperationValidation {
  allowed: boolean;
  autoExecute: boolean;
  reason: string;
  confidence: number;
  riskLevel: 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL';
  requiredAction: 'AUTO_EXECUTE' | 'PENDING_REVIEW' | 'HUMAN_ONLY';
  subscriptionLevel: 'FREE' | 'BASIC' | 'PROFESSIONAL' | 'ENTERPRISE';
  warnings: string[];
}

export interface IBatchOperationDataSource {
  createBatchOperation(params: {
    tenantId: string;
    shopId: string;
    operatorId: string;
    operatorName: string;
    operationType: string;
    targetType: 'PRODUCT' | 'AD_CAMPAIGN' | 'AD_CREATIVE';
    targetIds: string[];
    subscriptionLevel?: string;
  }): Promise<BatchOperationRecord>;

  validateBatchOperation(params: {
    tenantId: string;
    shopId: string;
    operatorId: string;
    operationType: string;
    targetIds: string[];
    targetType: 'PRODUCT' | 'AD_CAMPAIGN' | 'AD_CREATIVE';
    subscriptionLevel?: string;
    estimatedImpact?: { amount?: number; quantity?: number };
  }): Promise<BatchOperationValidation>;

  executeBatchOperation(batchId: string, params: any): Promise<{
    success: boolean;
    processedCount: number;
    errorCount: number;
  }>;

  confirmBatchOperation(batchId: string): Promise<{
    success: boolean;
    batchId: string;
  }>;

  cancelBatchOperation(batchId: string): Promise<{
    success: boolean;
  }>;

  getBatchOperationHistory(query: BatchOperationQuery): Promise<{
    records: BatchOperationRecord[];
    total: number;
  }>;

  getBatchOperation(batchId: string): Promise<BatchOperationRecord | null>;

  batchEditPrice(params: {
    tenantId: string;
    shopId: string;
    operatorId: string;
    productIds: string[];
    priceChange: { type: 'ABSOLUTE' | 'PERCENTAGE'; value: number };
  }): Promise<any>;

  batchEditInventory(params: {
    tenantId: string;
    shopId: string;
    operatorId: string;
    productIds: string[];
    inventoryChange: { type: 'ABSOLUTE' | 'PERCENTAGE'; value: number };
  }): Promise<any>;
}

class ApiBatchOperationDataSource implements IBatchOperationDataSource {
  async createBatchOperation(params: {
    tenantId: string;
    shopId: string;
    operatorId: string;
    operatorName: string;
    operationType: string;
    targetType: 'PRODUCT' | 'AD_CAMPAIGN' | 'AD_CREATIVE';
    targetIds: string[];
    subscriptionLevel?: string;
  }): Promise<BatchOperationRecord> {
    const response = await http.post('/api/v1/batch/create', params);
    return response.data;
  }

  async validateBatchOperation(params: {
    tenantId: string;
    shopId: string;
    operatorId: string;
    operationType: string;
    targetIds: string[];
    targetType: 'PRODUCT' | 'AD_CAMPAIGN' | 'AD_CREATIVE';
    subscriptionLevel?: string;
    estimatedImpact?: { amount?: number; quantity?: number };
  }): Promise<BatchOperationValidation> {
    const response = await http.post('/api/v1/batch/validate', params);
    return response.data;
  }

  async executeBatchOperation(batchId: string, params: any): Promise<{
    success: boolean;
    processedCount: number;
    errorCount: number;
  }> {
    const response = await http.post(`/api/v1/batch/${batchId}/execute`, params);
    return response.data;
  }

  async confirmBatchOperation(batchId: string): Promise<{
    success: boolean;
    batchId: string;
  }> {
    const response = await http.post(`/api/v1/batch/${batchId}/confirm`);
    return response.data;
  }

  async cancelBatchOperation(batchId: string): Promise<{
    success: boolean;
  }> {
    const response = await http.post(`/api/v1/batch/${batchId}/cancel`);
    return response.data;
  }

  async getBatchOperationHistory(query: BatchOperationQuery): Promise<{
    records: BatchOperationRecord[];
    total: number;
  }> {
    const response = await http.get('/api/v1/batch/history', { params: query });
    return response.data;
  }

  async getBatchOperation(batchId: string): Promise<BatchOperationRecord | null> {
    const response = await http.get(`/api/v1/batch/${batchId}`);
    return response.data;
  }

  async batchEditPrice(params: {
    tenantId: string;
    shopId: string;
    operatorId: string;
    productIds: string[];
    priceChange: { type: 'ABSOLUTE' | 'PERCENTAGE'; value: number };
  }): Promise<any> {
    const response = await http.post('/api/v1/batch/edit/price', params);
    return response.data;
  }

  async batchEditInventory(params: {
    tenantId: string;
    shopId: string;
    operatorId: string;
    productIds: string[];
    inventoryChange: { type: 'ABSOLUTE' | 'PERCENTAGE'; value: number };
  }): Promise<any> {
    const response = await http.post('/api/v1/batch/edit/inventory', params);
    return response.data;
  }
}

class MockBatchOperationDataSource implements IBatchOperationDataSource {
  private mockRecords: BatchOperationRecord[] = [];

  async createBatchOperation(params: {
    tenantId: string;
    shopId: string;
    operatorId: string;
    operatorName: string;
    operationType: string;
    targetType: 'PRODUCT' | 'AD_CAMPAIGN' | 'AD_CREATIVE';
    targetIds: string[];
    subscriptionLevel?: string;
  }): Promise<BatchOperationRecord> {
    const record: BatchOperationRecord = {
      id: `batch-${Date.now()}`,
      tenantId: params.tenantId,
      shopId: params.shopId,
      operatorId: params.operatorId,
      operatorName: params.operatorName,
      operationType: params.operationType,
      status: 'PENDING',
      targetType: params.targetType,
      targetIds: params.targetIds,
      totalCount: params.targetIds.length,
      successCount: 0,
      failedCount: 0,
      aiConfidence: 0.85,
      aiReason: 'Mock AI分析结果',
      riskLevel: 'LOW',
      subscriptionLevel: params.subscriptionLevel as any || 'BASIC',
      aiAutoExecuted: false,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    };
    this.mockRecords.push(record);
    return record;
  }

  async validateBatchOperation(params: {
    tenantId: string;
    shopId: string;
    operatorId: string;
    operationType: string;
    targetIds: string[];
    targetType: 'PRODUCT' | 'AD_CAMPAIGN' | 'AD_CREATIVE';
    subscriptionLevel?: string;
    estimatedImpact?: { amount?: number; quantity?: number };
  }): Promise<BatchOperationValidation> {
    const subscriptionLevel = params.subscriptionLevel || 'BASIC';
    const confidence = subscriptionLevel === 'ENTERPRISE' ? 0.9 :
                       subscriptionLevel === 'PROFESSIONAL' ? 0.75 :
                       subscriptionLevel === 'BASIC' ? 0.6 : 0.4;

    return {
      allowed: true,
      autoExecute: confidence >= 0.6,
      reason: confidence >= 0.6 ? 'AI自动执行' : '需要人工确认',
      confidence,
      riskLevel: params.targetIds.length > 50 ? 'MEDIUM' : 'LOW',
      requiredAction: confidence >= 0.6 ? 'AUTO_EXECUTE' : 'PENDING_REVIEW',
      subscriptionLevel: subscriptionLevel as any,
      warnings: [],
    };
  }

  async executeBatchOperation(batchId: string, params: any): Promise<{
    success: boolean;
    processedCount: number;
    errorCount: number;
  }> {
    await new Promise(resolve => setTimeout(resolve, 1000));
    return {
      success: true,
      processedCount: 10,
      errorCount: 0,
    };
  }

  async confirmBatchOperation(batchId: string): Promise<{
    success: boolean;
    batchId: string;
  }> {
    return { success: true, batchId };
  }

  async cancelBatchOperation(batchId: string): Promise<{
    success: boolean;
  }> {
    return { success: true };
  }

  async getBatchOperationHistory(query: BatchOperationQuery): Promise<{
    records: BatchOperationRecord[];
    total: number;
  }> {
    return {
      records: this.mockRecords,
      total: this.mockRecords.length,
    };
  }

  async getBatchOperation(batchId: string): Promise<BatchOperationRecord | null> {
    return this.mockRecords.find(r => r.id === batchId) || null;
  }

  async batchEditPrice(params: {
    tenantId: string;
    shopId: string;
    operatorId: string;
    productIds: string[];
    priceChange: { type: 'ABSOLUTE' | 'PERCENTAGE'; value: number };
  }): Promise<any> {
    await new Promise(resolve => setTimeout(resolve, 500));
    return {
      success: true,
      results: params.productIds.map(id => ({
        productId: id,
        success: true,
        beforePrice: 100,
        afterPrice: params.priceChange.type === 'ABSOLUTE'
          ? params.priceChange.value
          : 100 * (1 + params.priceChange.value / 100),
      })),
    };
  }

  async batchEditInventory(params: {
    tenantId: string;
    shopId: string;
    operatorId: string;
    productIds: string[];
    inventoryChange: { type: 'ABSOLUTE' | 'PERCENTAGE'; value: number };
  }): Promise<any> {
    await new Promise(resolve => setTimeout(resolve, 500));
    return {
      success: true,
      results: params.productIds.map(id => ({
        productId: id,
        success: true,
        beforeInventory: 50,
        afterInventory: params.inventoryChange.type === 'ABSOLUTE'
          ? params.inventoryChange.value
          : Math.round(50 * (1 + params.inventoryChange.value / 100)),
      })),
    };
  }
}

const USE_MOCK = process.env.REACT_APP_USE_MOCK === 'true';

export const batchOperationDataSource: IBatchOperationDataSource = USE_MOCK
  ? new MockBatchOperationDataSource()
  : new ApiBatchOperationDataSource();
