// E2E 테스트용 공정분류 규칙 (스크린/슬랫/절곡)
export const processClassificationRules = [
  {
    id: 'RULE-E2E-001',
    ruleName: '스크린 공정 분류',
    ruleCode: 'SCR-CLASSIFY',
    conditions: [
      { field: 'category', operator: 'equals', value: '스크린' },
      { field: 'productName', operator: 'contains', value: '스크린' }
    ],
    conditionLogic: 'OR',
    targetProcess: 'P-001',
    targetProcessName: '스크린',
    workSheetType: 'WORK-SCREEN',
    priority: 1,
    isActive: true,
    description: '품목 카테고리가 스크린이거나 품명에 스크린이 포함된 경우',
    createdAt: '2025-12-16',
  },
  {
    id: 'RULE-E2E-002',
    ruleName: '슬랫 공정 분류',
    ruleCode: 'SLAT-CLASSIFY',
    conditions: [
      { field: 'category', operator: 'equals', value: '슬랫' },
      { field: 'productName', operator: 'contains', value: '슬랫' },
      { field: 'productName', operator: 'contains', value: '그릴' }
    ],
    conditionLogic: 'OR',
    targetProcess: 'P-003',
    targetProcessName: '슬랫',
    workSheetType: 'WORK-SLAT',
    priority: 2,
    isActive: true,
    description: '품목 카테고리가 슬랫이거나 품명에 슬랫/그릴이 포함된 경우',
    createdAt: '2025-12-16',
  },
  {
    id: 'RULE-E2E-003',
    ruleName: '절곡 공정 분류',
    ruleCode: 'BEND-CLASSIFY',
    conditions: [
      { field: 'category', operator: 'equals', value: '절곡' },
      { field: 'productName', operator: 'contains', value: '절곡' },
      { field: 'productName', operator: 'contains', value: '포밍' }
    ],
    conditionLogic: 'OR',
    targetProcess: 'P-002',
    targetProcessName: '절곡',
    workSheetType: 'WORK-BENDING',
    priority: 3,
    isActive: true,
    description: '품목 카테고리가 절곡이거나 품명에 절곡/포밍이 포함된 경우',
    createdAt: '2025-12-16',
  }
];

// 품목 → 공정 자동 분류 함수
export const classifyItemToProcess = (item) => {
  for (const rule of processClassificationRules) {
    if (!rule.isActive) continue;

    let matched = false;
    const conditionResults = rule.conditions.map(cond => {
      const fieldValue = item[cond.field] || '';
      switch (cond.operator) {
        case 'equals':
          return fieldValue === cond.value;
        case 'contains':
          return fieldValue.includes(cond.value);
        case 'startsWith':
          return fieldValue.startsWith(cond.value);
        default:
          return false;
      }
    });

    if (rule.conditionLogic === 'AND') {
      matched = conditionResults.every(r => r);
    } else {
      matched = conditionResults.some(r => r);
    }

    if (matched) {
      return {
        processId: rule.targetProcess,
        processName: rule.targetProcessName,
        workSheetType: rule.workSheetType,
        matchedRule: rule.ruleName
      };
    }
  }

  return {
    processId: 'P-000',
    processName: '미분류',
    workSheetType: 'WORK-DEFAULT',
    matchedRule: null
  };
};

// E2E 디버깅 추적 로그 시스템
class E2EDebugLog {
  constructor() {
    this.logs = [];
    this.maxLogs = 100;
  }

  add(type, step, message, data = null) {
    const logEntry = {
      id: `LOG-${Date.now()}-${Math.random().toString(36).substr(2, 5)}`,
      timestamp: new Date().toISOString(),
      type, // info, success, warning, error
      step, // 견적산출, 수주전환, 공정분리 등
      message,
      data: data ? JSON.stringify(data, null, 2) : null
    };
    this.logs.unshift(logEntry);
    if (this.logs.length > this.maxLogs) {
      this.logs.pop();
    }
    console.log(`[E2E ${type.toUpperCase()}] ${step}: ${message}`, data || '');
    return logEntry;
  }

  quoteCalc(quoteId, params, result) {
    return this.add('info', '견적산출', `견적 ${quoteId} 자동산출 완료`, { params, result });
  }

  orderConvert(quoteId, orderId) {
    return this.add('success', '수주전환', `견적 ${quoteId} → 수주 ${orderId} 전환 완료`, { quoteId, orderId });
  }

  orderConfirm(orderId, confirmType) {
    return this.add('success', '수주확정', `수주 ${orderId} ${confirmType} 완료`, { orderId, confirmType });
  }

  productionOrder(orderId, productionOrderId) {
    return this.add('info', '생산지시', `수주 ${orderId} → 생산지시 ${productionOrderId} 발행`, { orderId, productionOrderId });
  }

  processSplit(productionOrderId, items, classificationResults) {
    return this.add('info', '공정분리', `생산지시 ${productionOrderId} 품목 ${items.length}건 공정분류 완료`, { productionOrderId, classificationResults });
  }

  workOrder(processName, workOrderId, itemCount) {
    return this.add('success', '작업지시', `${processName} 공정 작업지시 ${workOrderId} 생성 (${itemCount}건)`, { processName, workOrderId, itemCount });
  }

  workResult(workOrderId, status, completedCount) {
    return this.add('success', '작업실적', `작업지시 ${workOrderId} ${status} (${completedCount}건 완료)`, { workOrderId, status, completedCount });
  }

  inspection(workOrderId, result, inspectorName) {
    return this.add('info', '품질검사', `작업지시 ${workOrderId} 검사 ${result}`, { workOrderId, result, inspectorName });
  }

  shipment(shipmentId, itemCount, customerName) {
    return this.add('success', '출하완료', `출하 ${shipmentId} 처리 완료 (${itemCount}건 → ${customerName})`, { shipmentId, itemCount, customerName });
  }

  error(step, message, errorData) {
    return this.add('error', step, message, errorData);
  }

  clear() {
    this.logs = [];
    console.log('[E2E] 디버깅 로그 초기화됨');
  }

  getLogs() {
    return [...this.logs];
  }

  getLogsByStep(step) {
    return this.logs.filter(log => log.step === step);
  }

  getLogsByType(type) {
    return this.logs.filter(log => log.type === type);
  }
}

export const e2eDebugLog = new E2EDebugLog();

// E2E 테스트 시나리오 실행 함수
export const runE2EScenario = (scenarioId, data) => {
  const scenarios = {
    'e2e-quote-calc': () => {
      const { quoteId, params } = data;
      // 수식 기반 자동산출 시뮬레이션
      const result = {
        W1: params.W0 + 140,
        H1: params.H0 + 350,
        M: ((params.W0 + 140) * (params.H0 + 350) / 1000000).toFixed(2),
      };
      e2eDebugLog.quoteCalc(quoteId, params, result);
      return { success: true, result };
    },

    'e2e-order-convert': () => {
      const { quoteId } = data;
      const orderId = `ORD-${Date.now()}`;
      e2eDebugLog.orderConvert(quoteId, orderId);
      return { success: true, orderId };
    },

    'e2e-order-confirm': () => {
      const { orderId, confirmType } = data;
      e2eDebugLog.orderConfirm(orderId, confirmType);
      return { success: true };
    },

    'e2e-production-order': () => {
      const { orderId } = data;
      const productionOrderId = `PO-${Date.now()}`;
      e2eDebugLog.productionOrder(orderId, productionOrderId);
      return { success: true, productionOrderId };
    },

    'e2e-process-split': () => {
      const { productionOrderId, items } = data;
      const classificationResults = items.map(item => ({
        itemId: item.id,
        ...classifyItemToProcess(item)
      }));
      e2eDebugLog.processSplit(productionOrderId, items, classificationResults);
      return { success: true, classificationResults };
    },

    'e2e-work-order': () => {
      const { processName, items } = data;
      const workOrderId = `WO-${processName.substring(0, 2).toUpperCase()}-${Date.now()}`;
      e2eDebugLog.workOrder(processName, workOrderId, items.length);
      return { success: true, workOrderId };
    },

    'e2e-work-result': () => {
      const { workOrderId, completedCount } = data;
      e2eDebugLog.workResult(workOrderId, '완료', completedCount);
      return { success: true };
    },

    'e2e-inspection': () => {
      const { workOrderId, result, inspectorName } = data;
      e2eDebugLog.inspection(workOrderId, result, inspectorName);
      return { success: true };
    },

    'e2e-shipment': () => {
      const { items, customerName } = data;
      const shipmentId = `SH-${Date.now()}`;
      e2eDebugLog.shipment(shipmentId, items.length, customerName);
      return { success: true, shipmentId };
    },

    'e2e-full-flow': () => {
      // 전체 E2E 플로우 실행
      e2eDebugLog.clear();

      // 1. 견적산출
      const quoteResult = runE2EScenario('e2e-quote-calc', {
        quoteId: 'KD-E2E-TEST',
        params: { W0: 3000, H0: 2500, QTY: 1 }
      });

      // 2. 수주전환
      const orderResult = runE2EScenario('e2e-order-convert', {
        quoteId: 'KD-E2E-TEST'
      });

      // 3. 수주확정
      runE2EScenario('e2e-order-confirm', {
        orderId: orderResult.orderId,
        confirmType: '입금확인'
      });

      // 4. 생산지시
      const poResult = runE2EScenario('e2e-production-order', {
        orderId: orderResult.orderId
      });

      // 5. 공정분리
      const splitResult = runE2EScenario('e2e-process-split', {
        productionOrderId: poResult.productionOrderId,
        items: [
          { id: 1, category: '스크린', productName: '스크린 셔터' },
          { id: 2, category: '슬랫', productName: '슬랫 방화문' },
          { id: 3, category: '절곡', productName: '절곡 부품' }
        ]
      });

      // 6. 작업지시 (공정별)
      const screenWO = runE2EScenario('e2e-work-order', {
        processName: '스크린',
        items: splitResult.classificationResults.filter(r => r.processName === '스크린')
      });

      const slatWO = runE2EScenario('e2e-work-order', {
        processName: '슬랫',
        items: splitResult.classificationResults.filter(r => r.processName === '슬랫')
      });

      const bendWO = runE2EScenario('e2e-work-order', {
        processName: '절곡',
        items: splitResult.classificationResults.filter(r => r.processName === '절곡')
      });

      // 7. 작업실적
      runE2EScenario('e2e-work-result', { workOrderId: screenWO.workOrderId, completedCount: 1 });
      runE2EScenario('e2e-work-result', { workOrderId: slatWO.workOrderId, completedCount: 1 });
      runE2EScenario('e2e-work-result', { workOrderId: bendWO.workOrderId, completedCount: 1 });

      // 8. 품질검사
      runE2EScenario('e2e-inspection', { workOrderId: screenWO.workOrderId, result: '합격', inspectorName: '검사자A' });

      // 9. 출하
      const shipmentResult = runE2EScenario('e2e-shipment', {
        items: [{ id: 1 }, { id: 2 }, { id: 3 }],
        customerName: 'E2E 테스트 고객'
      });

      return {
        success: true,
        summary: {
          quoteResult,
          orderResult,
          poResult,
          splitResult,
          workOrders: [screenWO, slatWO, bendWO],
          shipmentResult
        },
        logs: e2eDebugLog.getLogs()
      };
    }
  };

  const scenario = scenarios[scenarioId];
  if (!scenario) {
    e2eDebugLog.error(scenarioId, `알 수 없는 시나리오: ${scenarioId}`);
    return { success: false, error: '알 수 없는 시나리오' };
  }

  try {
    return scenario();
  } catch (error) {
    e2eDebugLog.error(scenarioId, error.message, { stack: error.stack });
    return { success: false, error: error.message };
  }
};
