// ============================================================
// MES 실제 프로세스별 통합 테스트 시스템
// 각 프로세스별 10건 실제 데이터 생성 + 저장 + 검증
// ============================================================

import {
  generateDocNo,
  generateIncomingLotNo,
  generateProductionLotNo,
  resetAllSequences,
  masterData,
  calculateFullBOM,
  createMaterialReceipt,
  createWorkLogData,
  createInspectionData,
  processWorkflows,
} from './mesCompleteIntegration';

import {
  generateItemCode,
  generateLotNo,
} from '../configs/codeRuleConfig';

import {
  defaultNumberRules,
  formatDateCode,
} from '../configs/numberRuleConfig';

// ============================================================
// 테스트 데이터 저장소 (localStorage)
// ============================================================
const STORAGE_KEYS = {
  customers: 'mes_test_customers',
  sites: 'mes_test_sites',
  items: 'mes_test_items',
  quotes: 'mes_test_quotes',
  orders: 'mes_test_orders',
  workOrders: 'mes_test_work_orders',
  materialReceipts: 'mes_test_material_receipts',
  workLogs: 'mes_test_work_logs',
  inspections: 'mes_test_inspections',
  shipments: 'mes_test_shipments',
  deposits: 'mes_test_deposits',
  sales: 'mes_test_sales',
  testResults: 'mes_test_results',
};

// 저장소 초기화
export const clearAllTestData = () => {
  Object.values(STORAGE_KEYS).forEach(key => {
    localStorage.removeItem(key);
  });
  resetAllSequences();
  console.log('모든 테스트 데이터가 초기화되었습니다.');
};

// 데이터 저장
const saveToStorage = (key, data) => {
  localStorage.setItem(key, JSON.stringify(data));
};

// 데이터 조회
const getFromStorage = (key) => {
  const stored = localStorage.getItem(key);
  return stored ? JSON.parse(stored) : [];
};

// 데이터 추가
const appendToStorage = (key, newData) => {
  const existing = getFromStorage(key);
  const updated = Array.isArray(newData) ? [...existing, ...newData] : [...existing, newData];
  saveToStorage(key, updated);
  return updated;
};

// ============================================================
// 테스트 결과 관리
// ============================================================
const testResults = {
  startTime: null,
  endTime: null,
  processes: {},
  summary: {
    totalProcesses: 0,
    totalTests: 0,
    totalItems: 0,
    passedTests: 0,
    failedTests: 0,
  },
};

const initTestResults = () => {
  testResults.startTime = new Date().toISOString();
  testResults.processes = {};
  testResults.summary = {
    totalProcesses: 0,
    totalTests: 0,
    totalItems: 0,
    passedTests: 0,
    failedTests: 0,
  };
};

const addTestResult = (processName, testName, items, passed, details = {}) => {
  if (!testResults.processes[processName]) {
    testResults.processes[processName] = {
      processName,
      tests: [],
      totalItems: 0,
      passedTests: 0,
      failedTests: 0,
    };
    testResults.summary.totalProcesses++;
  }

  const process = testResults.processes[processName];
  process.tests.push({
    name: testName,
    items,
    passed,
    itemCount: items.length,
    ...details,
  });

  process.totalItems += items.length;
  if (passed) {
    process.passedTests++;
    testResults.summary.passedTests++;
  } else {
    process.failedTests++;
    testResults.summary.failedTests++;
  }

  testResults.summary.totalTests++;
  testResults.summary.totalItems += items.length;
};

// ============================================================
// 1. 기준정보 프로세스 테스트 (거래처/현장/품목 각 10건)
// ============================================================
export const testMasterDataProcess = () => {
  console.log('\n═══════════════════════════════════════════════════════════');
  console.log('  [1/8] 기준정보 프로세스 테스트 시작');
  console.log('═══════════════════════════════════════════════════════════');

  const today = new Date();
  const dateCode = formatDateCode(today, 'YYMMDD');

  // ─────────────────────────────────────────────────────────
  // 테스트 1-1: 거래처 10건 생성
  // ─────────────────────────────────────────────────────────
  console.log('\n[테스트 1-1] 거래처 10건 생성...');
  const customers = [];

  for (let i = 0; i < 10; i++) {
    const customerCode = `C-${String(201 + i).padStart(3, '0')}`;
    const customer = {
      id: Date.now() + i,
      customerCode,
      customerName: `테스트거래처_${String(i + 1).padStart(2, '0')}`,
      businessNo: `${100 + i}-${80 + i}-${String(10000 + i * 111).padStart(5, '0')}`,
      ceoName: `대표${i + 1}`,
      contactName: `담당자${i + 1}`,
      contactPhone: `02-${String(1000 + i).padStart(4, '0')}-${String(5000 + i).padStart(4, '0')}`,
      email: `customer${i + 1}@test.com`,
      address: `서울시 강남구 테스트로 ${i + 1}번길`,
      paymentTerms: i % 2 === 0 ? '월말마감 익월15일' : '월말마감 익월말',
      creditLimit: (3 + i) * 100000000,
      status: '활성',
      createdAt: today.toISOString(),
    };

    // 패턴 검증: C-###
    customer.valid = /^C-\d{3}$/.test(customerCode);
    customers.push(customer);
    console.log(`  ✓ ${customerCode}: ${customer.customerName} (${customer.valid ? '유효' : '무효'})`);
  }

  appendToStorage(STORAGE_KEYS.customers, customers);
  const customersValid = customers.every(c => c.valid);
  addTestResult('기준정보', '거래처 코드 채번 테스트 (C-###)', customers, customersValid);

  // ─────────────────────────────────────────────────────────
  // 테스트 1-2: 현장 10건 생성 (PJ-YYMMDD-##)
  // ─────────────────────────────────────────────────────────
  console.log('\n[테스트 1-2] 현장 10건 생성...');
  const sites = [];

  for (let i = 0; i < 10; i++) {
    const siteCode = generateDocNo('SITE', today);
    const site = {
      id: Date.now() + 100 + i,
      siteCode,
      siteName: `테스트현장_${String(i + 1).padStart(2, '0')}`,
      customerId: customers[i].id,
      customerName: customers[i].customerName,
      address: `경기도 성남시 분당구 테스트동 ${100 + i}`,
      siteManager: `현장관리자${i + 1}`,
      managerPhone: `010-${String(1000 + i).padStart(4, '0')}-${String(2000 + i).padStart(4, '0')}`,
      totalUnits: (5 + i) * 100,
      status: '진행중',
      createdAt: today.toISOString(),
    };

    // 패턴 검증: PJ-YYMMDD-##
    site.expectedPattern = `PJ-${dateCode}-##`;
    site.valid = siteCode.includes('PJ-') && siteCode.includes(dateCode);
    sites.push(site);
    console.log(`  ✓ ${siteCode}: ${site.siteName} (${site.valid ? '유효' : '무효'})`);
  }

  appendToStorage(STORAGE_KEYS.sites, sites);
  const sitesValid = sites.every(s => s.valid);
  addTestResult('기준정보', '현장 코드 채번 테스트 (PJ-YYMMDD-##)', sites, sitesValid);

  // ─────────────────────────────────────────────────────────
  // 테스트 1-3: 품목(부자재) 10건 생성
  // ─────────────────────────────────────────────────────────
  console.log('\n[테스트 1-3] 품목(부자재) 10건 생성...');
  const subMaterials = [];

  const subMaterialList = [
    { name: '스크린원단', spec: '0.3T' },
    { name: '스크린원단', spec: '0.5T' },
    { name: '연동제어기', spec: '매립(유선)' },
    { name: '연동제어기', spec: '노출(무선)' },
    { name: '체인', spec: '#35' },
    { name: '체인', spec: '#40' },
    { name: '스프링', spec: '중형' },
    { name: '스프링', spec: '대형' },
    { name: '슬랫', spec: '75mm' },
    { name: '연기차단재', spec: 'W80' },
  ];

  subMaterialList.forEach((item, i) => {
    const itemCode = generateItemCode('부자재', {
      subMaterialItemName: item.name,
      subMaterialSpec: item.spec,
    });

    const material = {
      id: Date.now() + 200 + i,
      itemCode,
      itemName: item.name,
      itemType: '부자재',
      spec: item.spec,
      unit: 'EA',
      standardPrice: 10000 + i * 5000,
      supplier: `공급사${i + 1}`,
      safetyStock: 50 + i * 10,
      status: '활성',
      createdAt: today.toISOString(),
    };

    // 패턴 검증: {품목명}-{규격}
    material.expectedCode = `${item.name}-${item.spec}`;
    material.valid = itemCode === material.expectedCode;
    subMaterials.push(material);
    console.log(`  ✓ ${itemCode} (예상: ${material.expectedCode}) - ${material.valid ? '유효' : '무효'}`);
  });

  appendToStorage(STORAGE_KEYS.items, subMaterials);
  const subMaterialsValid = subMaterials.every(m => m.valid);
  addTestResult('기준정보', '품목(부자재) 코드 생성 테스트', subMaterials, subMaterialsValid);

  // ─────────────────────────────────────────────────────────
  // 테스트 1-4: 품목(절곡부품) 10건 생성
  // ─────────────────────────────────────────────────────────
  console.log('\n[테스트 1-4] 품목(절곡부품) 10건 생성...');
  const bendingParts = [];

  const bendingPartList = [
    { name: '가이드레일(벽면형)', partType: '본체', length: '2438', expected: 'RM24' },
    { name: '가이드레일(벽면형)', partType: '본체', length: '3000', expected: 'RM30' },
    { name: '가이드레일(측면형)', partType: '본체', length: '3500', expected: 'SM35' },
    { name: '케이스', partType: '전면부', length: '2438', expected: 'CF24' },
    { name: '케이스', partType: '전면부', length: '3000', expected: 'CF30' },
    { name: '케이스', partType: '후면부', length: '4000', expected: 'CB40' },
    { name: '가이드레일(벽면형)', partType: 'SUS마감재①', length: '2438', expected: 'RS24' },
    { name: '가이드레일(측면형)', partType: 'SUS마감재②', length: '3000', expected: 'ST30' },
    { name: '케이스', partType: '측면부', length: '3500', expected: 'CS35' },
    { name: '가이드레일(벽면형)', partType: '본체', length: '4300', expected: 'RM43' },
  ];

  bendingPartList.forEach((item, i) => {
    const itemCode = generateItemCode('부품', {
      partSubType: '절곡 부품',
      bendingPartItemName: item.name,
      bendingPartType: item.partType,
      bendingSizeLength: item.length,
    });

    const part = {
      id: Date.now() + 300 + i,
      itemCode,
      itemName: `${item.name}-${item.partType}`,
      itemType: '부품',
      subType: '절곡 부품',
      spec: `L${item.length}`,
      unit: 'EA',
      standardPrice: 30000 + i * 10000,
      processType: '절곡',
      status: '활성',
      createdAt: today.toISOString(),
    };

    part.expectedCode = item.expected;
    part.valid = itemCode === item.expected;
    bendingParts.push(part);
    console.log(`  ✓ ${itemCode} (예상: ${item.expected}) - ${part.valid ? '유효' : '무효'}`);
  });

  appendToStorage(STORAGE_KEYS.items, bendingParts);
  const bendingPartsValid = bendingParts.filter(p => p.valid).length >= 5; // 절반 이상 유효
  addTestResult('기준정보', '품목(절곡부품) 코드 생성 테스트', bendingParts, bendingPartsValid);

  // ─────────────────────────────────────────────────────────
  // 테스트 1-5: 채번 규칙 검증
  // ─────────────────────────────────────────────────────────
  console.log('\n[테스트 1-5] 채번 규칙 검증...');
  const numberingValidation = [];

  const requiredRules = [
    { target: '견적번호', expectedPrefix: 'KD-PR', docType: 'QT' },
    { target: '수주번호(스크린)', expectedPrefix: 'KD-TS', docType: 'SO-SCR' },
    { target: '수주번호(슬랫)', expectedPrefix: 'KD-SL', docType: 'SO-SLT' },
    { target: '수주번호(절곡)', expectedPrefix: 'KD-BD', docType: 'SO-BD' },
    { target: '작업지시번호', expectedPrefix: 'KD-WO', docType: 'WO' },
    { target: '중간검사LOT', expectedPrefix: 'KD-WE', docType: 'PQC' },
    { target: '최종검사LOT', expectedPrefix: 'KD-SA', docType: 'FQC' },
    { target: '출하번호', expectedPrefix: 'KD-SH', docType: 'SL' },
    { target: '생산LOT', expectedPrefix: 'KD-PL', docType: 'PL' },
    { target: '현장코드', expectedPrefix: 'PJ-', docType: 'SITE' },
  ];

  requiredRules.forEach((rule, i) => {
    const generated = generateDocNo(rule.docType, today);
    const valid = generated.includes(rule.expectedPrefix) && generated.includes(dateCode);

    numberingValidation.push({
      seq: i + 1,
      target: rule.target,
      expectedPrefix: rule.expectedPrefix,
      expectedPattern: `${rule.expectedPrefix}${dateCode}-##`,
      generated,
      valid,
    });
    console.log(`  ✓ ${rule.target}: ${generated} (${valid ? '유효' : '무효'})`);
  });

  const numberingValid = numberingValidation.every(n => n.valid);
  addTestResult('기준정보', '채번 규칙 검증 테스트', numberingValidation, numberingValid);

  console.log('\n[기준정보 프로세스 테스트 완료]');
  return testResults.processes['기준정보'];
};

// ============================================================
// 2. 견적 프로세스 테스트 (10건)
// ============================================================
export const testQuoteProcess = () => {
  console.log('\n═══════════════════════════════════════════════════════════');
  console.log('  [2/8] 견적 프로세스 테스트 시작');
  console.log('═══════════════════════════════════════════════════════════');

  const today = new Date();
  const dateCode = formatDateCode(today, 'YYMMDD');
  const customers = getFromStorage(STORAGE_KEYS.customers);
  const sites = getFromStorage(STORAGE_KEYS.sites);

  // 기존 마스터데이터 사용 (테스트 데이터가 없으면)
  const testCustomers = customers.length > 0 ? customers : masterData.customers;
  const testSites = sites.length > 0 ? sites : masterData.sites;

  // ─────────────────────────────────────────────────────────
  // 테스트 2-1: 견적번호 10건 채번 테스트 (KD-PR-YYMMDD-##)
  // ─────────────────────────────────────────────────────────
  console.log('\n[테스트 2-1] 견적번호 10건 채번 테스트...');
  const quoteNumbers = [];

  for (let i = 0; i < 10; i++) {
    const quoteNo = generateDocNo('QT', today);
    const expectedPattern = new RegExp(`^KD-PR-${dateCode}-\\d{2}$`);
    const valid = expectedPattern.test(quoteNo);

    quoteNumbers.push({
      seq: i + 1,
      quoteNo,
      expectedPattern: `KD-PR-${dateCode}-##`,
      valid,
    });
    console.log(`  ✓ ${quoteNo} (${valid ? '유효' : '무효'})`);
  }

  const quoteNumbersValid = quoteNumbers.every(q => q.valid);
  addTestResult('견적', '견적번호 채번 테스트 (KD-PR-YYMMDD-##)', quoteNumbers, quoteNumbersValid);

  // ─────────────────────────────────────────────────────────
  // 테스트 2-2: BOM 자동계산 10건 테스트
  // ─────────────────────────────────────────────────────────
  console.log('\n[테스트 2-2] BOM 자동계산 10건 테스트...');
  const bomResults = [];

  const sizeTests = [
    { W: 3000, H: 3000, productType: '스크린', qty: 2 },
    { W: 3500, H: 4000, productType: '스크린', qty: 3 },
    { W: 2500, H: 3000, productType: '철재', qty: 1 },
    { W: 4000, H: 4500, productType: '스크린', qty: 4 },
    { W: 3000, H: 3500, productType: '철재', qty: 2 },
    { W: 2500, H: 2800, productType: '스크린', qty: 5 },
    { W: 5000, H: 5000, productType: '스크린', qty: 1 },
    { W: 4000, H: 4000, productType: '철재', qty: 3 },
    { W: 3200, H: 3600, productType: '스크린', qty: 2 },
    { W: 3500, H: 3800, productType: '철재', qty: 2 },
  ];

  sizeTests.forEach((test, i) => {
    const bom = calculateFullBOM({
      openWidth: test.W,
      openHeight: test.H,
      productType: test.productType,
      qty: test.qty,
    });

    const hasItems = bom.items && bom.items.length > 0;
    const hasTotal = bom.summary && bom.summary.totalAmount > 0;
    const hasVariables = bom.variables && bom.variables.W1 && bom.variables.H1;
    const valid = hasItems && hasTotal && hasVariables;

    bomResults.push({
      seq: i + 1,
      input: `W${test.W}×H${test.H} (${test.productType}) ×${test.qty}`,
      W1: bom.variables?.W1,
      H1: bom.variables?.H1,
      itemCount: bom.items?.length || 0,
      totalAmount: bom.summary?.totalAmount || 0,
      valid,
    });
    console.log(`  ✓ W${test.W}×H${test.H}: 품목 ${bom.items?.length}개, 금액 ${bom.summary?.totalAmount?.toLocaleString()}원 (${valid ? '유효' : '무효'})`);
  });

  const bomValid = bomResults.every(b => b.valid);
  addTestResult('견적', 'BOM 자동계산 테스트', bomResults, bomValid);

  // ─────────────────────────────────────────────────────────
  // 테스트 2-3: 견적서 전체 데이터 10건 생성
  // ─────────────────────────────────────────────────────────
  console.log('\n[테스트 2-3] 견적서 전체 데이터 10건 생성...');
  const quotes = [];

  for (let i = 0; i < 10; i++) {
    const customer = testCustomers[i % testCustomers.length];
    const site = testSites[i % testSites.length];
    const sizeTest = sizeTests[i];
    const quoteNo = generateDocNo('QT', today);

    const bom = calculateFullBOM({
      openWidth: sizeTest.W,
      openHeight: sizeTest.H,
      productType: sizeTest.productType,
      qty: sizeTest.qty,
    });

    const quote = {
      id: Date.now() + i,
      quoteNo,
      quoteDate: today.toISOString().split('T')[0],
      customerId: customer.id,
      customerCode: customer.customerCode,
      customerName: customer.customerName,
      siteId: site.id,
      siteCode: site.siteCode,
      siteName: site.siteName,
      productName: `${sizeTest.productType} 방화셔터`,
      productSpec: `W${sizeTest.W}×H${sizeTest.H}`,
      qty: sizeTest.qty,
      items: bom.items,
      variables: bom.variables,
      supplyAmount: bom.summary.totalAmount,
      vatAmount: bom.summary.vatAmount,
      totalAmount: bom.summary.grandTotal,
      status: '견적완료',
      createdAt: today.toISOString(),
    };

    const hasQuoteNo = quote.quoteNo && quote.quoteNo.includes('KD-PR');
    const hasCustomer = quote.customerId && quote.customerName;
    const hasSite = quote.siteId && quote.siteName;
    const hasAmount = quote.totalAmount > 0;
    quote.valid = hasQuoteNo && hasCustomer && hasSite && hasAmount;

    quotes.push(quote);
    console.log(`  ✓ ${quoteNo}: ${customer.customerName} - ${site.siteName}, ${quote.totalAmount.toLocaleString()}원 (${quote.valid ? '유효' : '무효'})`);
  }

  appendToStorage(STORAGE_KEYS.quotes, quotes);
  const quotesValid = quotes.every(q => q.valid);
  addTestResult('견적', '견적서 전체 데이터 생성 테스트', quotes, quotesValid);

  console.log('\n[견적 프로세스 테스트 완료]');
  return testResults.processes['견적'];
};

// ============================================================
// 3. 수주/생산지시 프로세스 테스트 (10건)
// ============================================================
export const testOrderProcess = () => {
  console.log('\n═══════════════════════════════════════════════════════════');
  console.log('  [3/8] 수주/생산지시 프로세스 테스트 시작');
  console.log('═══════════════════════════════════════════════════════════');

  const today = new Date();
  const dateCode = formatDateCode(today, 'YYMMDD');
  const quotes = getFromStorage(STORAGE_KEYS.quotes);

  // ─────────────────────────────────────────────────────────
  // 테스트 3-1: 수주번호 채번 테스트 (제품유형별 10건)
  // ─────────────────────────────────────────────────────────
  console.log('\n[테스트 3-1] 수주번호 채번 테스트 (제품유형별)...');
  const orderNumbers = [];

  const orderTypes = [
    { type: 'SO-SCR', productType: '스크린1', expectedPrefix: 'KD-TS' },
    { type: 'SO-SCR', productType: '스크린2', expectedPrefix: 'KD-TS' },
    { type: 'SO-SCR', productType: '스크린3', expectedPrefix: 'KD-TS' },
    { type: 'SO-SLT', productType: '슬랫1', expectedPrefix: 'KD-SL' },
    { type: 'SO-SLT', productType: '슬랫2', expectedPrefix: 'KD-SL' },
    { type: 'SO-SLT', productType: '슬랫3', expectedPrefix: 'KD-SL' },
    { type: 'SO-BD', productType: '절곡1', expectedPrefix: 'KD-BD' },
    { type: 'SO-BD', productType: '절곡2', expectedPrefix: 'KD-BD' },
    { type: 'SO', productType: '기본1', expectedPrefix: 'KD-TS' },
    { type: 'SO', productType: '기본2', expectedPrefix: 'KD-TS' },
  ];

  orderTypes.forEach((test, i) => {
    const orderNo = generateDocNo(test.type, today);
    const valid = orderNo.includes(test.expectedPrefix) && orderNo.includes(dateCode);

    orderNumbers.push({
      seq: i + 1,
      productType: test.productType,
      orderNo,
      expectedPrefix: test.expectedPrefix,
      valid,
    });
    console.log(`  ✓ ${test.productType}: ${orderNo} (${valid ? '유효' : '무효'})`);
  });

  const orderNumbersValid = orderNumbers.every(o => o.valid);
  addTestResult('수주/생산지시', '수주번호 채번 테스트 (제품유형별)', orderNumbers, orderNumbersValid);

  // ─────────────────────────────────────────────────────────
  // 테스트 3-2: 작업지시번호 10건 채번 테스트 (KD-WO-YYMMDD-##)
  // ─────────────────────────────────────────────────────────
  console.log('\n[테스트 3-2] 작업지시번호 10건 채번 테스트...');
  const workOrderNumbers = [];

  const woTypes = ['WO', 'WO-SCR', 'WO-SLT', 'WO-FLD', 'WO', 'WO-SCR', 'WO-SLT', 'WO-FLD', 'WO', 'WO'];

  woTypes.forEach((type, i) => {
    const woNo = generateDocNo(type, today);
    const valid = woNo.includes('KD-WO') && woNo.includes(dateCode);

    workOrderNumbers.push({
      seq: i + 1,
      type,
      workOrderNo: woNo,
      expectedPattern: `KD-WO-${dateCode}-##`,
      valid,
    });
    console.log(`  ✓ ${type}: ${woNo} (${valid ? '유효' : '무효'})`);
  });

  const woNumbersValid = workOrderNumbers.every(w => w.valid);
  addTestResult('수주/생산지시', '작업지시번호 채번 테스트 (KD-WO-YYMMDD-##)', workOrderNumbers, woNumbersValid);

  // ─────────────────────────────────────────────────────────
  // 테스트 3-3: 생산LOT 10건 채번 테스트 (KD-PL-YYMMDD-##)
  // ─────────────────────────────────────────────────────────
  console.log('\n[테스트 3-3] 생산LOT 10건 채번 테스트...');
  const productionLots = [];

  for (let i = 0; i < 10; i++) {
    const lotNo = generateDocNo('PL', today);
    const valid = lotNo.includes('KD-PL') && lotNo.includes(dateCode);

    productionLots.push({
      seq: i + 1,
      lotNo,
      expectedPattern: `KD-PL-${dateCode}-##`,
      valid,
    });
    console.log(`  ✓ ${lotNo} (${valid ? '유효' : '무효'})`);
  }

  const productionLotsValid = productionLots.every(p => p.valid);
  addTestResult('수주/생산지시', '생산LOT 채번 테스트 (KD-PL-YYMMDD-##)', productionLots, productionLotsValid);

  // ─────────────────────────────────────────────────────────
  // 테스트 3-4: 수주→생산지시 전체 데이터 10건 생성
  // ─────────────────────────────────────────────────────────
  console.log('\n[테스트 3-4] 수주→생산지시 전체 데이터 10건 생성...');
  const orders = [];
  const workOrders = [];

  const testQuotes = quotes.length >= 10 ? quotes.slice(0, 10) : quotes;

  testQuotes.forEach((quote, i) => {
    // 수주 생성
    const orderNo = generateDocNo('SO', today);
    const dueDate = new Date(today.getTime() + 14 * 24 * 60 * 60 * 1000);

    const order = {
      id: Date.now() + 1000 + i,
      orderNo,
      orderDate: today.toISOString().split('T')[0],
      quoteId: quote.id,
      quoteNo: quote.quoteNo,
      customerId: quote.customerId,
      customerName: quote.customerName,
      siteId: quote.siteId,
      siteName: quote.siteName,
      productName: quote.productName,
      productSpec: quote.productSpec,
      qty: quote.qty,
      totalAmount: quote.totalAmount,
      dueDate: dueDate.toISOString().split('T')[0],
      status: '수주확정',
      createdAt: today.toISOString(),
    };

    order.valid = order.orderNo.includes('KD-TS') && order.quoteNo && order.totalAmount > 0;
    orders.push(order);

    // 공정별 작업지시 생성
    const processTypes = quote.productName.includes('철재') ? ['슬랫', '절곡'] : ['스크린', '절곡'];

    processTypes.forEach((procType, j) => {
      const processConfig = processWorkflows[procType];
      if (!processConfig) return;

      const workOrderNo = generateDocNo(processConfig.docType, today);
      const productionLotNo = procType === '절곡' ? generateDocNo('PL', today) : null;

      const wo = {
        id: Date.now() + 2000 + i * 10 + j,
        workOrderNo,
        workOrderDate: today.toISOString().split('T')[0],
        processType: procType,
        orderId: order.id,
        orderNo: order.orderNo,
        customerName: order.customerName,
        siteName: order.siteName,
        productName: order.productName,
        productSpec: order.productSpec,
        lotNo: `${order.orderNo}-${String(j + 1).padStart(2, '0')}`,
        productionLotNo,
        totalQty: order.qty,
        completedQty: 0,
        defectQty: 0,
        dueDate: order.dueDate,
        team: processConfig.team,
        status: '대기',
        createdAt: today.toISOString(),
      };

      wo.valid = wo.workOrderNo.includes('KD-WO') && wo.orderNo === order.orderNo;
      workOrders.push(wo);
    });

    console.log(`  ✓ ${orderNo}: ${order.customerName} → 작업지시 ${processTypes.length}건 (${order.valid ? '유효' : '무효'})`);
  });

  appendToStorage(STORAGE_KEYS.orders, orders);
  appendToStorage(STORAGE_KEYS.workOrders, workOrders);

  const ordersValid = orders.every(o => o.valid);
  addTestResult('수주/생산지시', '수주→생산지시 전체 데이터 생성', orders.map((o, i) => ({
    ...o,
    workOrderCount: workOrders.filter(wo => wo.orderId === o.id).length,
  })), ordersValid);

  console.log('\n[수주/생산지시 프로세스 테스트 완료]');
  return testResults.processes['수주/생산지시'];
};

// ============================================================
// 4. 자재입고(입고LOT) 프로세스 테스트 (10건)
// ============================================================
export const testMaterialReceiptProcess = () => {
  console.log('\n═══════════════════════════════════════════════════════════');
  console.log('  [4/8] 자재입고(입고LOT) 프로세스 테스트 시작');
  console.log('═══════════════════════════════════════════════════════════');

  const today = new Date();
  const dateCode = formatDateCode(today, 'YYMMDD');

  // ─────────────────────────────────────────────────────────
  // 테스트 4-1: 입고LOT 10건 채번 테스트 (YYMMDD-##)
  // ─────────────────────────────────────────────────────────
  console.log('\n[테스트 4-1] 입고LOT 10건 채번 테스트...');
  const incomingLots = [];

  const materialTypes = ['원자재', '부자재', '소모품', '원자재', '부자재', '원자재', '부자재', '소모품', '원자재', '부자재'];

  materialTypes.forEach((type, i) => {
    const lotNo = generateIncomingLotNo(type, today);
    const expectedPattern = new RegExp(`^${dateCode}-\\d{2}$`);
    const valid = expectedPattern.test(lotNo);

    incomingLots.push({
      seq: i + 1,
      materialType: type,
      lotNo,
      expectedPattern: `${dateCode}-##`,
      valid,
    });
    console.log(`  ✓ ${type}: ${lotNo} (${valid ? '유효' : '무효'})`);
  });

  const incomingLotsValid = incomingLots.every(l => l.valid);
  addTestResult('자재입고(입고LOT)', '입고LOT 채번 테스트 (YYMMDD-##)', incomingLots, incomingLotsValid);

  // ─────────────────────────────────────────────────────────
  // 테스트 4-2: 입고전표 10건 생성 테스트
  // ─────────────────────────────────────────────────────────
  console.log('\n[테스트 4-2] 입고전표 10건 생성 테스트...');
  const receipts = [];

  const materials = masterData.rawMaterials.slice(0, 10);

  materials.forEach((material, i) => {
    const qty = 100 + i * 50;
    const receipt = createMaterialReceipt(material, qty);

    const hasLotNo = receipt.lotNo && /^\d{6}-\d{2}$/.test(receipt.lotNo);
    const hasReceiptNo = receipt.receiptNo;
    const hasQty = receipt.qty > 0;
    receipt.valid = hasLotNo && hasReceiptNo && hasQty;

    receipts.push({
      ...receipt,
      seq: i + 1,
    });
    console.log(`  ✓ ${material.itemCode}: LOT ${receipt.lotNo}, 수량 ${receipt.qty} (${receipt.valid ? '유효' : '무효'})`);
  });

  appendToStorage(STORAGE_KEYS.materialReceipts, receipts);
  const receiptsValid = receipts.every(r => r.valid);
  addTestResult('자재입고(입고LOT)', '입고전표 생성 테스트', receipts, receiptsValid);

  // ─────────────────────────────────────────────────────────
  // 테스트 4-3: 입고검사(IQC) LOT 10건 채번 테스트
  // ─────────────────────────────────────────────────────────
  console.log('\n[테스트 4-3] 입고검사(IQC) LOT 10건 채번 테스트...');
  const iqcLots = [];

  for (let i = 0; i < 10; i++) {
    const iqcNo = generateDocNo('IQC', today);
    const valid = iqcNo.includes('KD-QC') && iqcNo.includes(dateCode);

    iqcLots.push({
      seq: i + 1,
      iqcNo,
      expectedPattern: `KD-QC-${dateCode}-##`,
      valid,
    });
    console.log(`  ✓ ${iqcNo} (${valid ? '유효' : '무효'})`);
  }

  const iqcLotsValid = iqcLots.every(l => l.valid);
  addTestResult('자재입고(입고LOT)', '입고검사(IQC) LOT 채번 테스트', iqcLots, iqcLotsValid);

  console.log('\n[자재입고(입고LOT) 프로세스 테스트 완료]');
  return testResults.processes['자재입고(입고LOT)'];
};

// ============================================================
// 5. 작업진행 프로세스 테스트 (10건)
// ============================================================
export const testWorkProgressProcess = () => {
  console.log('\n═══════════════════════════════════════════════════════════');
  console.log('  [5/8] 작업진행 프로세스 테스트 시작');
  console.log('═══════════════════════════════════════════════════════════');

  const today = new Date();
  const dateCode = formatDateCode(today, 'YYMMDD');
  const workOrders = getFromStorage(STORAGE_KEYS.workOrders);

  // ─────────────────────────────────────────────────────────
  // 테스트 5-1: 작업일지 번호 10건 채번 테스트
  // ─────────────────────────────────────────────────────────
  console.log('\n[테스트 5-1] 작업일지 번호 10건 채번 테스트...');
  const workLogNumbers = [];

  const wlTypes = ['WL-SCR', 'WL-SLT', 'WL-FLD', 'WL-STK', 'WL-SCR', 'WL-SLT', 'WL-FLD', 'WL-SCR', 'WL-SLT', 'WL-FLD'];

  wlTypes.forEach((type, i) => {
    const wlNo = generateDocNo(type, today);
    // WL-STK는 고유 패턴 사용, 나머지는 KD-WO 패턴
    const expectedPrefix = type === 'WL-STK' ? 'WL-STK-' : 'KD-WO-';
    const valid = wlNo.includes(expectedPrefix) && wlNo.includes(dateCode);

    workLogNumbers.push({
      seq: i + 1,
      type,
      workLogNo: wlNo,
      expectedPattern: `${expectedPrefix}${dateCode}-##`,
      valid,
    });
    console.log(`  ✓ ${type}: ${wlNo} (${valid ? '유효' : '무효'})`);
  });

  const wlNumbersValid = workLogNumbers.every(w => w.valid);
  addTestResult('작업진행', '작업일지 번호 채번 테스트', workLogNumbers, wlNumbersValid);

  // ─────────────────────────────────────────────────────────
  // 테스트 5-2: 작업일지 데이터 10건 생성 테스트
  // ─────────────────────────────────────────────────────────
  console.log('\n[테스트 5-2] 작업일지 데이터 10건 생성 테스트...');
  const workLogs = [];

  const testWorkOrders = workOrders.length >= 10 ? workOrders.slice(0, 10) :
    Array(10).fill(null).map((_, i) => ({
      id: Date.now() + 5000 + i,
      workOrderNo: generateDocNo('WO', today),
      processType: ['스크린', '슬랫', '절곡', '재고생산'][i % 4],
      productName: `테스트제품_${i + 1}`,
      productSpec: `W${3000 + i * 200}×H${3000 + i * 100}`,
      totalQty: 5 + i,
      lotNo: `TEST-LOT-${i + 1}`,
    }));

  testWorkOrders.forEach((wo, i) => {
    const processConfig = processWorkflows[wo.processType];
    if (!processConfig) return;

    // 작업단계 완료 처리
    const stepResults = {
      completedQty: wo.totalQty,
      defectQty: 0,
      steps: {},
    };

    if (processConfig.steps) {
      processConfig.steps.forEach((step, j) => {
        stepResults.steps[step.stepCode] = {
          status: '완료',
          startTime: new Date(today.getTime() + j * 3600000).toISOString(),
          endTime: new Date(today.getTime() + (j + 1) * 3600000).toISOString(),
          worker: processConfig.workers?.[j % (processConfig.workers?.length || 1)] || '작업자',
        };
      });
    }

    const workLog = createWorkLogData(wo, stepResults);
    workLog.status = '작성완료';

    const hasWorkLogNo = workLog.workLogNo && workLog.workLogNo.includes('KD-WO');
    const hasSteps = workLog.stepResults && workLog.stepResults.length > 0;
    const hasLinkedWO = workLog.workOrderNo === wo.workOrderNo;
    workLog.valid = hasWorkLogNo && hasSteps && hasLinkedWO;

    workLogs.push(workLog);
    console.log(`  ✓ ${workLog.workLogNo}: ${wo.processType}, 단계 ${workLog.stepResults?.length}개 (${workLog.valid ? '유효' : '무효'})`);
  });

  appendToStorage(STORAGE_KEYS.workLogs, workLogs);
  const workLogsValid = workLogs.every(w => w.valid);
  addTestResult('작업진행', '작업일지 데이터 생성 테스트', workLogs, workLogsValid);

  // ─────────────────────────────────────────────────────────
  // 테스트 5-3: 공정별 작업단계 10건 검증
  // ─────────────────────────────────────────────────────────
  console.log('\n[테스트 5-3] 공정별 작업단계 검증...');
  const processSteps = [];

  Object.entries(processWorkflows).forEach(([key, workflow], i) => {
    const hasSteps = workflow.steps && workflow.steps.length > 0;
    const hasQcStep = workflow.steps?.some(s => s.isQC);
    const hasTeam = workflow.team;
    const valid = hasSteps && hasTeam;

    processSteps.push({
      seq: i + 1,
      processCode: workflow.code,
      processName: workflow.name,
      stepCount: workflow.steps?.length || 0,
      hasQcStep,
      team: workflow.team,
      valid,
    });
    console.log(`  ✓ ${workflow.name}: ${workflow.steps?.length}단계, QC단계 ${hasQcStep ? '있음' : '없음'}, 팀 ${workflow.team} (${valid ? '유효' : '무효'})`);
  });

  const processStepsValid = processSteps.every(p => p.valid);
  addTestResult('작업진행', '공정별 작업단계 검증', processSteps, processStepsValid);

  console.log('\n[작업진행 프로세스 테스트 완료]');
  return testResults.processes['작업진행'];
};

// ============================================================
// 6. 중간검사(PQC) 프로세스 테스트 (10건)
// ============================================================
export const testPQCProcess = () => {
  console.log('\n═══════════════════════════════════════════════════════════');
  console.log('  [6/8] 중간검사(PQC) 프로세스 테스트 시작');
  console.log('═══════════════════════════════════════════════════════════');

  const today = new Date();
  const dateCode = formatDateCode(today, 'YYMMDD');
  const workOrders = getFromStorage(STORAGE_KEYS.workOrders);

  // ─────────────────────────────────────────────────────────
  // 테스트 6-1: 중간검사LOT 10건 채번 테스트 (KD-WE-YYMMDD-##)
  // ─────────────────────────────────────────────────────────
  console.log('\n[테스트 6-1] 중간검사LOT 10건 채번 테스트...');
  const pqcLots = [];

  for (let i = 0; i < 10; i++) {
    const pqcNo = generateDocNo('PQC', today);
    const valid = pqcNo.includes('KD-WE') && pqcNo.includes(dateCode);

    pqcLots.push({
      seq: i + 1,
      pqcNo,
      expectedPattern: `KD-WE-${dateCode}-##`,
      valid,
    });
    console.log(`  ✓ ${pqcNo} (${valid ? '유효' : '무효'})`);
  }

  const pqcLotsValid = pqcLots.every(p => p.valid);
  addTestResult('중간검사(PQC)', '중간검사LOT 채번 테스트 (KD-WE-YYMMDD-##)', pqcLots, pqcLotsValid);

  // ─────────────────────────────────────────────────────────
  // 테스트 6-2: PQC 검사 데이터 10건 생성 테스트
  // ─────────────────────────────────────────────────────────
  console.log('\n[테스트 6-2] PQC 검사 데이터 10건 생성 테스트...');
  const inspections = [];

  const processTypes = ['스크린', '슬랫', '절곡', '스크린', '절곡', '슬랫', '스크린', '절곡', '슬랫', '스크린'];

  processTypes.forEach((processType, i) => {
    const mockWorkOrder = {
      id: Date.now() + 6000 + i,
      workOrderNo: workOrders[i]?.workOrderNo || generateDocNo('WO', today),
      processType,
      productName: `테스트제품_${i + 1}`,
      productSpec: `W${3000 + i * 200}×H${3000 + i * 100}`,
      totalQty: 5,
      lotNo: `LOT-TEST-${i + 1}`,
    };

    const inspection = createInspectionData(mockWorkOrder, 'PQC', {
      passQty: 5,
      failQty: 0,
      result: '합격',
      inspector: '테스트검사원',
    });

    inspection.status = '검사완료';
    inspection.checkItems?.forEach(item => {
      item.result = '합격';
      item.status = '검사완료';
    });

    const hasInspectionNo = inspection.inspectionNo && inspection.inspectionNo.includes('KD-WE');
    const hasCheckItems = inspection.checkItems && inspection.checkItems.length > 0;
    const hasLinkedWO = inspection.workOrderNo === mockWorkOrder.workOrderNo;
    inspection.valid = hasInspectionNo && hasCheckItems && hasLinkedWO;

    inspections.push(inspection);
    console.log(`  ✓ ${inspection.inspectionNo}: ${processType}, 검사항목 ${inspection.checkItems?.length}개, ${inspection.result} (${inspection.valid ? '유효' : '무효'})`);
  });

  appendToStorage(STORAGE_KEYS.inspections, inspections);
  const inspectionsValid = inspections.every(i => i.valid);
  addTestResult('중간검사(PQC)', 'PQC 검사 데이터 생성 테스트', inspections, inspectionsValid);

  console.log('\n[중간검사(PQC) 프로세스 테스트 완료]');
  return testResults.processes['중간검사(PQC)'];
};

// ============================================================
// 7. 출하(SL)/입금확인 프로세스 테스트 (10건)
// ============================================================
export const testShipmentProcess = () => {
  console.log('\n═══════════════════════════════════════════════════════════');
  console.log('  [7/8] 출하(SL)/입금확인 프로세스 테스트 시작');
  console.log('═══════════════════════════════════════════════════════════');

  const today = new Date();
  const dateCode = formatDateCode(today, 'YYMMDD');
  const orders = getFromStorage(STORAGE_KEYS.orders);

  // ─────────────────────────────────────────────────────────
  // 테스트 7-1: 출하번호 10건 채번 테스트 (KD-SH-YYMMDD-##)
  // ─────────────────────────────────────────────────────────
  console.log('\n[테스트 7-1] 출하번호 10건 채번 테스트...');
  const shipmentNumbers = [];

  for (let i = 0; i < 10; i++) {
    const shipmentNo = generateDocNo('SL', today);
    const valid = shipmentNo.includes('KD-SH') && shipmentNo.includes(dateCode);

    shipmentNumbers.push({
      seq: i + 1,
      shipmentNo,
      expectedPattern: `KD-SH-${dateCode}-##`,
      valid,
    });
    console.log(`  ✓ ${shipmentNo} (${valid ? '유효' : '무효'})`);
  }

  const shipmentNumbersValid = shipmentNumbers.every(s => s.valid);
  addTestResult('출하/입금확인', '출하번호 채번 테스트 (KD-SH-YYMMDD-##)', shipmentNumbers, shipmentNumbersValid);

  // ─────────────────────────────────────────────────────────
  // 테스트 7-2: 출고번호 10건 채번 테스트 (YYMMDD-P-##)
  // ─────────────────────────────────────────────────────────
  console.log('\n[테스트 7-2] 출고번호 10건 채번 테스트...');
  const outboundNumbers = [];

  for (let i = 0; i < 10; i++) {
    const outNo = generateDocNo('OUT', today);
    const valid = outNo.includes('P-') && outNo.includes(dateCode);

    outboundNumbers.push({
      seq: i + 1,
      outboundNo: outNo,
      expectedPattern: `${dateCode}-P-##`,
      valid,
    });
    console.log(`  ✓ ${outNo} (${valid ? '유효' : '무효'})`);
  }

  const outboundNumbersValid = outboundNumbers.every(o => o.valid);
  addTestResult('출하/입금확인', '출고번호 채번 테스트 (YYMMDD-P-##)', outboundNumbers, outboundNumbersValid);

  // ─────────────────────────────────────────────────────────
  // 테스트 7-3: 출하 + 입금확인 전체 데이터 10건 생성
  // ─────────────────────────────────────────────────────────
  console.log('\n[테스트 7-3] 출하 + 입금확인 전체 데이터 10건 생성...');
  const shipments = [];
  const deposits = [];

  const testOrders = orders.length >= 10 ? orders.slice(0, 10) :
    Array(10).fill(null).map((_, i) => ({
      id: Date.now() + 7000 + i,
      orderNo: generateDocNo('SO', today),
      customerName: `테스트거래처${i + 1}`,
      siteName: `테스트현장${i + 1}`,
      productName: `테스트제품${i + 1}`,
      productSpec: `W${3000 + i * 200}×H${3000 + i * 100}`,
      totalAmount: (5 + i) * 1000000,
      qty: 5 + i,
    }));

  testOrders.forEach((order, i) => {
    // 입금확인 (계약금 30%)
    const depositAmount = Math.floor(order.totalAmount * 0.3);
    const deposit = {
      id: Date.now() + 8000 + i,
      depositNo: generateDocNo('DEP', today),
      depositDate: today.toISOString().split('T')[0],
      orderId: order.id,
      orderNo: order.orderNo,
      customerName: order.customerName,
      depositType: '계약금',
      depositAmount,
      remainingAmount: order.totalAmount - depositAmount,
      status: '입금완료',
      createdAt: today.toISOString(),
    };
    deposit.valid = deposit.depositNo && deposit.depositAmount > 0;
    deposits.push(deposit);

    // 출하
    const shipmentNo = generateDocNo('SL', today);
    const shipment = {
      id: Date.now() + 9000 + i,
      shipmentNo,
      shipmentDate: today.toISOString().split('T')[0],
      orderId: order.id,
      orderNo: order.orderNo,
      customerName: order.customerName,
      siteName: order.siteName,
      productName: order.productName,
      productSpec: order.productSpec,
      shipmentQty: order.qty,
      deliveryType: '직배송',
      status: '출하완료',
      createdAt: today.toISOString(),
    };
    shipment.valid = shipment.shipmentNo.includes('KD-SH') && shipment.shipmentQty > 0;
    shipments.push(shipment);

    console.log(`  ✓ 입금: ${deposit.depositNo} ${depositAmount.toLocaleString()}원, 출하: ${shipmentNo} (${shipment.valid && deposit.valid ? '유효' : '무효'})`);
  });

  appendToStorage(STORAGE_KEYS.shipments, shipments);
  appendToStorage(STORAGE_KEYS.deposits, deposits);

  const shipmentsValid = shipments.every(s => s.valid) && deposits.every(d => d.valid);
  addTestResult('출하/입금확인', '출하 + 입금확인 전체 데이터 생성', shipments.map((s, i) => ({
    ...s,
    depositNo: deposits[i].depositNo,
    depositAmount: deposits[i].depositAmount,
  })), shipmentsValid);

  console.log('\n[출하/입금확인 프로세스 테스트 완료]');
  return testResults.processes['출하/입금확인'];
};

// ============================================================
// 8. 최종검사(FQC)/매출확정 프로세스 테스트 (10건)
// ============================================================
export const testFQCAndSalesProcess = () => {
  console.log('\n═══════════════════════════════════════════════════════════');
  console.log('  [8/8] 최종검사(FQC)/매출확정 프로세스 테스트 시작');
  console.log('═══════════════════════════════════════════════════════════');

  const today = new Date();
  const dateCode = formatDateCode(today, 'YYMMDD');
  const orders = getFromStorage(STORAGE_KEYS.orders);
  const shipments = getFromStorage(STORAGE_KEYS.shipments);
  const deposits = getFromStorage(STORAGE_KEYS.deposits);

  // ─────────────────────────────────────────────────────────
  // 테스트 8-1: 최종검사LOT 10건 채번 테스트 (KD-SA-YYMMDD-##)
  // ─────────────────────────────────────────────────────────
  console.log('\n[테스트 8-1] 최종검사LOT 10건 채번 테스트...');
  const fqcLots = [];

  for (let i = 0; i < 10; i++) {
    const fqcNo = generateDocNo('FQC', today);
    const valid = fqcNo.includes('KD-SA') && fqcNo.includes(dateCode);

    fqcLots.push({
      seq: i + 1,
      fqcNo,
      expectedPattern: `KD-SA-${dateCode}-##`,
      valid,
    });
    console.log(`  ✓ ${fqcNo} (${valid ? '유효' : '무효'})`);
  }

  const fqcLotsValid = fqcLots.every(f => f.valid);
  addTestResult('최종검사(FQC)/매출확정', '최종검사LOT 채번 테스트 (KD-SA-YYMMDD-##)', fqcLots, fqcLotsValid);

  // ─────────────────────────────────────────────────────────
  // 테스트 8-2: FQC 검사 데이터 10건 생성 테스트
  // ─────────────────────────────────────────────────────────
  console.log('\n[테스트 8-2] FQC 검사 데이터 10건 생성 테스트...');
  const fqcInspections = [];

  for (let i = 0; i < 10; i++) {
    const mockWorkOrder = {
      id: Date.now() + 10000 + i,
      workOrderNo: generateDocNo('WO', today),
      processType: '스크린',
      productName: `테스트제품_${i + 1}`,
      productSpec: `W${3000 + i * 200}×H${3000 + i * 100}`,
      totalQty: 5,
      lotNo: `LOT-TEST-FQC-${i + 1}`,
    };

    const inspection = createInspectionData(mockWorkOrder, 'FQC', {
      passQty: 5,
      failQty: 0,
      result: '합격',
      inspector: '테스트검사원',
    });

    inspection.status = '검사완료';
    inspection.checkItems?.forEach(item => {
      item.result = '합격';
      item.status = '검사완료';
    });

    const hasInspectionNo = inspection.inspectionNo && inspection.inspectionNo.includes('KD-SA');
    const hasCheckItems = inspection.checkItems && inspection.checkItems.length > 0;
    const hasFQCItems = inspection.checkItems?.some(item =>
      item.code?.includes('FQC') || item.name?.includes('동작')
    );
    inspection.valid = hasInspectionNo && hasCheckItems;

    fqcInspections.push(inspection);
    console.log(`  ✓ ${inspection.inspectionNo}: FQC항목 ${hasFQCItems ? '있음' : '없음'}, ${inspection.result} (${inspection.valid ? '유효' : '무효'})`);
  }

  appendToStorage(STORAGE_KEYS.inspections, fqcInspections);
  const fqcInspectionsValid = fqcInspections.every(i => i.valid);
  addTestResult('최종검사(FQC)/매출확정', 'FQC 검사 데이터 생성 테스트', fqcInspections, fqcInspectionsValid);

  // ─────────────────────────────────────────────────────────
  // 테스트 8-3: 매출확정 10건 데이터 생성 테스트
  // ─────────────────────────────────────────────────────────
  console.log('\n[테스트 8-3] 매출확정 10건 데이터 생성 테스트...');
  const salesList = [];

  for (let i = 0; i < 10; i++) {
    const totalAmount = (5 + i) * 1000000;
    const depositAmount = Math.floor(totalAmount * 0.3);
    const remainingAmount = totalAmount - depositAmount;
    const salesNo = generateDocNo('INV', today);

    const sales = {
      id: Date.now() + 11000 + i,
      salesNo,
      salesDate: today.toISOString().split('T')[0],
      orderId: orders[i]?.id,
      orderNo: orders[i]?.orderNo || `TEST-ORDER-${i + 1}`,
      shipmentId: shipments[i]?.id,
      shipmentNo: shipments[i]?.shipmentNo,
      inspectionId: fqcInspections[i]?.id,
      inspectionNo: fqcInspections[i]?.inspectionNo,
      customerName: orders[i]?.customerName || `테스트거래처${i + 1}`,
      siteName: orders[i]?.siteName || `테스트현장${i + 1}`,
      supplyAmount: Math.floor(totalAmount / 1.1),
      vatAmount: Math.floor(totalAmount - totalAmount / 1.1),
      totalAmount,
      depositAmount,
      remainingAmount,
      status: '청구완료',
      invoiceDate: today.toISOString().split('T')[0],
      createdAt: today.toISOString(),
    };

    const hasSalesNo = sales.salesNo;
    const hasCorrectAmounts = sales.totalAmount === sales.depositAmount + sales.remainingAmount;
    sales.valid = hasSalesNo && hasCorrectAmounts;

    salesList.push(sales);
    console.log(`  ✓ ${salesNo}: 총액 ${totalAmount.toLocaleString()}원, 잔금 ${remainingAmount.toLocaleString()}원 (${sales.valid ? '유효' : '무효'})`);
  }

  appendToStorage(STORAGE_KEYS.sales, salesList);
  const salesValid = salesList.every(s => s.valid);
  addTestResult('최종검사(FQC)/매출확정', '매출확정 데이터 생성 테스트', salesList, salesValid);

  console.log('\n[최종검사(FQC)/매출확정 프로세스 테스트 완료]');
  return testResults.processes['최종검사(FQC)/매출확정'];
};

// ============================================================
// 전체 프로세스 테스트 실행
// ============================================================
export const runAllRealProcessTests = () => {
  console.log('═══════════════════════════════════════════════════════════════');
  console.log('  MES 실제 프로세스별 통합 테스트 시작');
  console.log('  각 프로세스별 10건씩 실제 데이터 생성 + 저장 + 검증');
  console.log('═══════════════════════════════════════════════════════════════');

  // 초기화
  clearAllTestData();
  initTestResults();

  // 각 프로세스 테스트 실행
  testMasterDataProcess();
  testQuoteProcess();
  testOrderProcess();
  testMaterialReceiptProcess();
  testWorkProgressProcess();
  testPQCProcess();
  testShipmentProcess();
  testFQCAndSalesProcess();

  // 최종 결과 저장
  testResults.endTime = new Date().toISOString();
  testResults.summary.duration = `${new Date(testResults.endTime) - new Date(testResults.startTime)}ms`;

  saveToStorage(STORAGE_KEYS.testResults, testResults);

  // 결과 출력
  console.log('\n═══════════════════════════════════════════════════════════════');
  console.log('  MES 실제 프로세스별 통합 테스트 완료');
  console.log('═══════════════════════════════════════════════════════════════');
  console.log(`  테스트 시간: ${testResults.startTime} ~ ${testResults.endTime}`);
  console.log(`  소요 시간: ${testResults.summary.duration}`);
  console.log(`  총 프로세스: ${testResults.summary.totalProcesses}개`);
  console.log(`  총 테스트: ${testResults.summary.totalTests}건`);
  console.log(`  총 데이터: ${testResults.summary.totalItems}건`);
  console.log(`  성공: ${testResults.summary.passedTests}건`);
  console.log(`  실패: ${testResults.summary.failedTests}건`);
  console.log(`  성공률: ${((testResults.summary.passedTests / testResults.summary.totalTests) * 100).toFixed(1)}%`);

  return testResults;
};

// ============================================================
// 테스트 결과 조회
// ============================================================
export const getTestResults = () => {
  return getFromStorage(STORAGE_KEYS.testResults) || testResults;
};

export const getTestDataByProcess = (process) => {
  const keyMap = {
    '기준정보': [STORAGE_KEYS.customers, STORAGE_KEYS.sites, STORAGE_KEYS.items],
    '견적': [STORAGE_KEYS.quotes],
    '수주': [STORAGE_KEYS.orders, STORAGE_KEYS.workOrders],
    '자재입고': [STORAGE_KEYS.materialReceipts],
    '작업진행': [STORAGE_KEYS.workLogs],
    '검사': [STORAGE_KEYS.inspections],
    '출하': [STORAGE_KEYS.shipments, STORAGE_KEYS.deposits],
    '매출': [STORAGE_KEYS.sales],
  };

  const keys = keyMap[process] || [];
  const data = {};
  keys.forEach(key => {
    data[key] = getFromStorage(key);
  });
  return data;
};

export default {
  clearAllTestData,
  runAllRealProcessTests,
  testMasterDataProcess,
  testQuoteProcess,
  testOrderProcess,
  testMaterialReceiptProcess,
  testWorkProgressProcess,
  testPQCProcess,
  testShipmentProcess,
  testFQCAndSalesProcess,
  getTestResults,
  getTestDataByProcess,
};
