// ============================================================
// MES 전체 시스템 통합 테스트
// 기준정보 → 거래처 → 현장 → 품목 → 단가 → 견적 → 수주 → 생산 → 검사 → 출하
// ============================================================

import {
  generateDocumentNumber,
  calculateBOM,
  processSteps,
  processAssignees,
  createWorkOrderFromOrder,
  createInspectionFromWorkOrder,
  createShipmentFromInspection,
} from './mesIntegrationUtils';

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

// ============================================================
// 1. 기준정보 마스터 데이터 (5개씩)
// ============================================================

/**
 * 거래처 마스터 5개
 */
export const testCustomers = [
  {
    id: 1,
    customerCode: 'C-001',
    customerName: '삼성물산(주)',
    customerType: '고객',
    businessNo: '124-81-00998',
    ceoName: '오세철',
    contactName: '김철수',
    contactPhone: '02-2145-5114',
    email: 'sales@samsung.co.kr',
    address: '서울시 강남구 삼성동 159',
    paymentTerms: '월말마감 익월 15일 결제',
    creditLimit: 500000000,
    status: '활성',
    createdAt: '2024-01-15',
  },
  {
    id: 2,
    customerCode: 'C-002',
    customerName: '현대건설(주)',
    customerType: '고객',
    businessNo: '101-81-03810',
    ceoName: '윤영준',
    contactName: '박영희',
    contactPhone: '02-746-1114',
    email: 'construction@hdec.co.kr',
    address: '서울시 종로구 율곡로 75',
    paymentTerms: '월말마감 익월 말일 결제',
    creditLimit: 800000000,
    status: '활성',
    createdAt: '2024-01-20',
  },
  {
    id: 3,
    customerCode: 'C-003',
    customerName: 'GS건설(주)',
    customerType: '고객',
    businessNo: '104-81-17992',
    ceoName: '허윤홍',
    contactName: '이정민',
    contactPhone: '02-728-1114',
    email: 'business@gsconst.co.kr',
    address: '서울시 강남구 논현로 508',
    paymentTerms: '월말마감 익월 15일 결제',
    creditLimit: 600000000,
    status: '활성',
    createdAt: '2024-02-01',
  },
  {
    id: 4,
    customerCode: 'C-004',
    customerName: '대우건설(주)',
    customerType: '고객',
    businessNo: '117-81-16765',
    ceoName: '백정완',
    contactName: '최민수',
    contactPhone: '02-2288-3500',
    email: 'sales@dwconst.co.kr',
    address: '서울시 중구 을지로 170',
    paymentTerms: '월말마감 익월 말일 결제',
    creditLimit: 400000000,
    status: '활성',
    createdAt: '2024-02-15',
  },
  {
    id: 5,
    customerCode: 'C-005',
    customerName: '롯데건설(주)',
    customerType: '고객',
    businessNo: '110-81-07367',
    ceoName: '하석주',
    contactName: '정수진',
    contactPhone: '02-2118-2114',
    email: 'contact@lotteconst.co.kr',
    address: '서울시 송파구 올림픽로 300',
    paymentTerms: '월말마감 익월 20일 결제',
    creditLimit: 550000000,
    status: '활성',
    createdAt: '2024-03-01',
  },
];

/**
 * 현장 마스터 5개 (거래처별 연결)
 */
export const testSites = [
  {
    id: 1,
    siteCode: 'S-001',
    siteName: '래미안 강남 포레스트',
    customerId: 1,
    customerName: '삼성물산(주)',
    address: '서울시 강남구 개포동 12-1',
    siteManager: '김현장',
    managerPhone: '010-1234-5678',
    constructionType: '아파트 신축',
    totalUnits: 850,
    startDate: '2024-03-01',
    expectedEndDate: '2026-06-30',
    status: '진행중',
  },
  {
    id: 2,
    siteCode: 'S-002',
    siteName: '힐스테이트 판교 센트럴',
    customerId: 2,
    customerName: '현대건설(주)',
    address: '경기도 성남시 분당구 판교동 789',
    siteManager: '박건축',
    managerPhone: '010-2345-6789',
    constructionType: '주상복합',
    totalUnits: 1200,
    startDate: '2024-01-15',
    expectedEndDate: '2026-12-31',
    status: '진행중',
  },
  {
    id: 3,
    siteCode: 'S-003',
    siteName: '자이 위례 에듀파크',
    customerId: 3,
    customerName: 'GS건설(주)',
    address: '경기도 성남시 수정구 위례동 456',
    siteManager: '이시공',
    managerPhone: '010-3456-7890',
    constructionType: '아파트 신축',
    totalUnits: 680,
    startDate: '2024-04-01',
    expectedEndDate: '2026-09-30',
    status: '진행중',
  },
  {
    id: 4,
    siteCode: 'S-004',
    siteName: '푸르지오 송도 마리나시티',
    customerId: 4,
    customerName: '대우건설(주)',
    address: '인천시 연수구 송도동 123',
    siteManager: '최대리',
    managerPhone: '010-4567-8901',
    constructionType: '아파트 신축',
    totalUnits: 1500,
    startDate: '2024-02-01',
    expectedEndDate: '2027-03-31',
    status: '진행중',
  },
  {
    id: 5,
    siteCode: 'S-005',
    siteName: '롯데캐슬 동탄 파크타운',
    customerId: 5,
    customerName: '롯데건설(주)',
    address: '경기도 화성시 동탄면 789-12',
    siteManager: '정과장',
    managerPhone: '010-5678-9012',
    constructionType: '대단지 아파트',
    totalUnits: 2200,
    startDate: '2024-05-01',
    expectedEndDate: '2027-06-30',
    status: '진행중',
  },
];

/**
 * 품목 마스터 - 제품 5개
 */
export const testProducts = [
  {
    id: 1,
    itemCode: '방화셔터 W3000×H3000',
    itemName: '방화셔터 W3000×H3000',
    itemType: '제품',
    category: '방화셔터',
    productType: '스크린',
    spec: 'W3000×H3000',
    unit: 'SET',
    standardPrice: 2850000,
    leadTime: 14,
    minOrderQty: 1,
    status: '활성',
  },
  {
    id: 2,
    itemCode: '방화셔터 W3500×H4000',
    itemName: '방화셔터 W3500×H4000',
    itemType: '제품',
    category: '방화셔터',
    productType: '스크린',
    spec: 'W3500×H4000',
    unit: 'SET',
    standardPrice: 3650000,
    leadTime: 14,
    minOrderQty: 1,
    status: '활성',
  },
  {
    id: 3,
    itemCode: '방화셔터(철재) W2500×H3000',
    itemName: '방화셔터(철재) W2500×H3000',
    itemType: '제품',
    category: '방화셔터',
    productType: '철재',
    spec: 'W2500×H3000',
    unit: 'SET',
    standardPrice: 3200000,
    leadTime: 21,
    minOrderQty: 1,
    status: '활성',
  },
  {
    id: 4,
    itemCode: '방화셔터 W4000×H4500',
    itemName: '방화셔터 W4000×H4500',
    itemType: '제품',
    category: '방화셔터',
    productType: '스크린',
    spec: 'W4000×H4500',
    unit: 'SET',
    standardPrice: 4250000,
    leadTime: 14,
    minOrderQty: 1,
    status: '활성',
  },
  {
    id: 5,
    itemCode: '방화셔터(철재) W3000×H3500',
    itemName: '방화셔터(철재) W3000×H3500',
    itemType: '제품',
    category: '방화셔터',
    productType: '철재',
    spec: 'W3000×H3500',
    unit: 'SET',
    standardPrice: 3850000,
    leadTime: 21,
    minOrderQty: 1,
    status: '활성',
  },
];

/**
 * 품목 마스터 - 부품(구매/조립/절곡) 각 5개씩
 */
export const testParts = {
  // 구매 부품 5개
  purchased: [
    {
      id: 101,
      itemCode: '전동개폐기-380V300KG',
      itemName: '전동개폐기',
      itemType: '부품',
      subType: '구매 부품',
      spec: '380V 300KG',
      unit: 'EA',
      standardPrice: 350000,
      supplier: '동양전기',
      leadTime: 7,
      status: '활성',
    },
    {
      id: 102,
      itemCode: '전동개폐기-380V500KG',
      itemName: '전동개폐기',
      itemType: '부품',
      subType: '구매 부품',
      spec: '380V 500KG',
      unit: 'EA',
      standardPrice: 480000,
      supplier: '동양전기',
      leadTime: 7,
      status: '활성',
    },
    {
      id: 103,
      itemCode: '연동제어기-매립(유선)',
      itemName: '연동제어기',
      itemType: '부품',
      subType: '구매 부품',
      spec: '매립(유선)',
      unit: 'EA',
      standardPrice: 65000,
      supplier: '세진전자',
      leadTime: 5,
      status: '활성',
    },
    {
      id: 104,
      itemCode: '브라켓-380×180',
      itemName: '브라켓',
      itemType: '부품',
      subType: '구매 부품',
      spec: '380×180',
      unit: 'SET',
      standardPrice: 25000,
      supplier: '한국철강',
      leadTime: 3,
      status: '활성',
    },
    {
      id: 105,
      itemCode: '감기샤프트-5인치-L4500',
      itemName: '감기샤프트(메인)',
      itemType: '부품',
      subType: '구매 부품',
      spec: '5인치 L4500',
      unit: 'EA',
      standardPrice: 120000,
      supplier: '대한샤프트',
      leadTime: 5,
      status: '활성',
    },
  ],
  // 조립 부품 5개
  assembly: [
    {
      id: 201,
      itemCode: '가이드레일 벽면형-1211*1111*24',
      itemName: '가이드레일 벽면형',
      itemType: '부품',
      subType: '조립 부품',
      spec: '1211*1111*2438',
      unit: 'EA',
      standardPrice: 85000,
      processType: '절곡',
      leadTime: 3,
      status: '활성',
    },
    {
      id: 202,
      itemCode: '가이드레일 벽면형-1211*1111*30',
      itemName: '가이드레일 벽면형',
      itemType: '부품',
      subType: '조립 부품',
      spec: '1211*1111*3000',
      unit: 'EA',
      standardPrice: 95000,
      processType: '절곡',
      leadTime: 3,
      status: '활성',
    },
    {
      id: 203,
      itemCode: '셔터박스 표준-3000*300*200',
      itemName: '셔터박스',
      itemType: '부품',
      subType: '조립 부품',
      spec: '3000*300*200',
      unit: 'EA',
      standardPrice: 180000,
      processType: '절곡',
      leadTime: 5,
      status: '활성',
    },
    {
      id: 204,
      itemCode: '개폐기조립체 300KG형',
      itemName: '개폐기조립체',
      itemType: '부품',
      subType: '조립 부품',
      spec: '300KG형',
      unit: 'SET',
      standardPrice: 450000,
      processType: '조립',
      leadTime: 2,
      status: '활성',
    },
    {
      id: 205,
      itemCode: '제어반조립체 매립형',
      itemName: '제어반조립체',
      itemType: '부품',
      subType: '조립 부품',
      spec: '매립형',
      unit: 'SET',
      standardPrice: 120000,
      processType: '조립',
      leadTime: 2,
      status: '활성',
    },
  ],
  // 절곡 부품 5개
  bending: [
    {
      id: 301,
      itemCode: 'RM24',
      itemName: '가이드레일(벽면형)-본체',
      itemType: '부품',
      subType: '절곡 부품',
      spec: 'L2438',
      unit: 'EA',
      standardPrice: 45000,
      processType: '절곡',
      leadTime: 2,
      status: '활성',
    },
    {
      id: 302,
      itemCode: 'RM30',
      itemName: '가이드레일(벽면형)-본체',
      itemType: '부품',
      subType: '절곡 부품',
      spec: 'L3000',
      unit: 'EA',
      standardPrice: 52000,
      processType: '절곡',
      leadTime: 2,
      status: '활성',
    },
    {
      id: 303,
      itemCode: 'CF24',
      itemName: '케이스-전면부',
      itemType: '부품',
      subType: '절곡 부품',
      spec: 'L2438',
      unit: 'EA',
      standardPrice: 85000,
      processType: '절곡',
      leadTime: 3,
      status: '활성',
    },
    {
      id: 304,
      itemCode: 'BS24',
      itemName: '하단마감재(스크린)-SUS',
      itemType: '부품',
      subType: '절곡 부품',
      spec: 'L2438',
      unit: 'EA',
      standardPrice: 38000,
      processType: '절곡',
      leadTime: 2,
      status: '활성',
    },
    {
      id: 305,
      itemCode: 'GI53',
      itemName: '연기차단재-화이바원단',
      itemType: '부품',
      subType: '절곡 부품',
      spec: 'W50×L3000',
      unit: 'EA',
      standardPrice: 12000,
      processType: '부자재',
      leadTime: 1,
      status: '활성',
    },
  ],
};

/**
 * 품목 마스터 - 원자재 5개
 */
export const testRawMaterials = [
  {
    id: 401,
    itemCode: '철판-EGI-1.2T',
    itemName: '아연도금강판',
    itemType: '원자재',
    spec: 'EGI 1.2T 4×8',
    unit: 'EA',
    standardPrice: 85000,
    supplier: '포스코',
    leadTime: 3,
    safetyStock: 50,
    status: '활성',
  },
  {
    id: 402,
    itemCode: '철판-EGI-1.6T',
    itemName: '아연도금강판',
    itemType: '원자재',
    spec: 'EGI 1.6T 4×8',
    unit: 'EA',
    standardPrice: 115000,
    supplier: '포스코',
    leadTime: 3,
    safetyStock: 30,
    status: '활성',
  },
  {
    id: 403,
    itemCode: '스크린원단-0.5T',
    itemName: '스크린 원단',
    itemType: '원자재',
    spec: '0.5T W1200',
    unit: 'M',
    standardPrice: 15000,
    supplier: '대한섬유',
    leadTime: 7,
    safetyStock: 500,
    status: '활성',
  },
  {
    id: 404,
    itemCode: '슬랫코일-50mm',
    itemName: '슬랫 코일',
    itemType: '원자재',
    spec: '50mm 백색',
    unit: 'KG',
    standardPrice: 4500,
    supplier: '한국알루미늄',
    leadTime: 5,
    safetyStock: 1000,
    status: '활성',
  },
  {
    id: 405,
    itemCode: '철판-SUS-1.0T',
    itemName: '스테인리스판',
    itemType: '원자재',
    spec: 'SUS304 1.0T',
    unit: 'EA',
    standardPrice: 180000,
    supplier: '포스코',
    leadTime: 5,
    safetyStock: 20,
    status: '활성',
  },
];

/**
 * 품목 마스터 - 소모품 5개
 */
export const testConsumables = [
  {
    id: 501,
    itemCode: '용접봉-3.2MM',
    itemName: '용접봉',
    itemType: '소모품',
    spec: '3.2mm 일반용',
    unit: 'KG',
    standardPrice: 8500,
    supplier: '한국용접',
    safetyStock: 100,
    status: '활성',
  },
  {
    id: 502,
    itemCode: '실리콘-백색',
    itemName: '실리콘',
    itemType: '소모품',
    spec: '백색 280ml',
    unit: 'EA',
    standardPrice: 3500,
    supplier: '한국실리콘',
    safetyStock: 200,
    status: '활성',
  },
  {
    id: 503,
    itemCode: '도장-회색',
    itemName: '스프레이 도장',
    itemType: '소모품',
    spec: '회색 400ml',
    unit: 'EA',
    standardPrice: 6500,
    supplier: '한국도료',
    safetyStock: 100,
    status: '활성',
  },
  {
    id: 504,
    itemCode: '장갑-면장갑',
    itemName: '면장갑',
    itemType: '소모품',
    spec: '표준형',
    unit: '켤레',
    standardPrice: 800,
    supplier: '안전용품',
    safetyStock: 500,
    status: '활성',
  },
  {
    id: 505,
    itemCode: '테이프-포장용',
    itemName: '포장테이프',
    itemType: '소모품',
    spec: '48mm×50M',
    unit: 'EA',
    standardPrice: 2500,
    supplier: '한국포장',
    safetyStock: 200,
    status: '활성',
  },
];

// ============================================================
// 2. 전체 프로세스 통합 테스트 실행
// ============================================================

/**
 * 단일 견적~출하 전체 프로세스 실행
 * @param {object} params - 테스트 파라미터
 * @returns {object} 전체 프로세스 결과
 */
export const runFullProcessTest = (params) => {
  const {
    customer,
    site,
    product,
    openWidth,
    openHeight,
    productType,
    qty,
    testNo,
  } = params;

  const today = new Date();
  const results = {
    testNo,
    testName: `통합테스트 #${testNo}: ${customer.customerName} - ${site.siteName}`,
    success: true,
    errors: [],
    data: {},
    timeline: [],
  };

  const logStep = (step, message, data = null) => {
    results.timeline.push({
      step,
      message,
      timestamp: new Date().toISOString(),
      data,
    });
    console.log(`[테스트 #${testNo}] ${step}: ${message}`);
  };

  try {
    // ─────────────────────────────────────────────────────────
    // STEP 1: 견적 생성 (채번관리 + BOM 자동계산)
    // ─────────────────────────────────────────────────────────
    logStep('견적생성', '견적번호 채번 및 BOM 자동계산 시작');

    const quoteNo = generateDocumentNumber('QT', today);
    const bom = calculateBOM({
      openWidth,
      openHeight,
      productType,
      shaftInch: openWidth > 4000 ? '6' : '5',
      installType: '벽면형',
      motorPower: '380',
      wireType: '유선',
      controllerType: '매립',
      qty,
    });

    const quote = {
      id: Date.now(),
      quoteNo,
      quoteDate: today.toISOString().split('T')[0],
      customerId: customer.id,
      customerName: customer.customerName,
      siteId: site.id,
      siteName: site.siteName,
      siteCode: site.siteCode,
      productName: `${productType} 셔터 W${openWidth}×H${openHeight}`,
      productSpec: `W${openWidth}×H${openHeight}`,
      qty,
      bomItems: bom.items,
      bomVariables: bom.variables,
      totalAmount: bom.summary.totalAmount * qty,
      status: '견적완료',
      createdAt: today.toISOString(),
    };

    results.data.quote = quote;
    logStep('견적완료', `견적번호: ${quoteNo}, BOM ${bom.items.length}품목, 금액: ${quote.totalAmount.toLocaleString()}원`, { quoteNo, bomCount: bom.items.length, amount: quote.totalAmount });

    // ─────────────────────────────────────────────────────────
    // STEP 2: 수주 전환 (견적 → 수주)
    // ─────────────────────────────────────────────────────────
    logStep('수주전환', '견적을 수주로 전환');

    const orderNo = generateDocumentNumber('SO', today);
    const dueDate = new Date(today.getTime() + 14 * 24 * 60 * 60 * 1000);

    const order = {
      id: Date.now() + 1,
      orderNo,
      orderDate: today.toISOString().split('T')[0],
      quoteId: quote.id,
      quoteNo: quote.quoteNo,
      customerId: customer.id,
      customerName: customer.customerName,
      siteId: site.id,
      siteName: site.siteName,
      siteCode: site.siteCode,
      items: [{
        productName: quote.productName,
        productSpec: quote.productSpec,
        width: openWidth,
        height: openHeight,
        productType,
        qty,
        unitPrice: quote.totalAmount / qty,
        amount: quote.totalAmount,
      }],
      totalQty: qty,
      totalAmount: quote.totalAmount,
      dueDate: dueDate.toISOString().split('T')[0],
      status: '수주확정',
      createdAt: today.toISOString(),
    };

    results.data.order = order;
    logStep('수주완료', `수주번호: ${orderNo}, 납기: ${order.dueDate}`, { orderNo, dueDate: order.dueDate });

    // ─────────────────────────────────────────────────────────
    // STEP 3: 작업지시 생성 (공정관리 연동)
    // ─────────────────────────────────────────────────────────
    logStep('작업지시', '공정별 작업지시 생성');

    const workOrders = [];
    const processTypes = productType === '스크린' ? ['스크린', '절곡'] : ['슬랫', '절곡'];

    processTypes.forEach((processType, idx) => {
      const wo = createWorkOrderFromOrder(order, {
        processType,
        workDate: today,
        splitNo: idx + 1,
      });
      workOrders.push(wo);
    });

    results.data.workOrders = workOrders;
    logStep('작업지시완료', `${workOrders.length}개 공정 작업지시 생성`, workOrders.map(wo => ({
      workOrderNo: wo.workOrderNo,
      processType: wo.processType,
      steps: Object.keys(wo.stepStatus),
    })));

    // ─────────────────────────────────────────────────────────
    // STEP 4: 작업자 진행 (작업단계별 상태 업데이트)
    // ─────────────────────────────────────────────────────────
    logStep('작업진행', '작업단계별 진행 시뮬레이션');

    const updatedWorkOrders = workOrders.map(wo => {
      const steps = Object.keys(wo.stepStatus);
      const updatedStepStatus = { ...wo.stepStatus };

      // 절반 단계까지 완료 처리
      const completedSteps = Math.ceil(steps.length / 2);
      steps.forEach((step, idx) => {
        if (idx < completedSteps) {
          updatedStepStatus[step] = {
            status: '완료',
            startTime: new Date(today.getTime() + idx * 60 * 60 * 1000).toISOString(),
            endTime: new Date(today.getTime() + (idx + 1) * 60 * 60 * 1000).toISOString(),
            worker: wo.assignees[idx % wo.assignees.length],
          };
        } else if (idx === completedSteps) {
          updatedStepStatus[step] = {
            status: '진행중',
            startTime: new Date(today.getTime() + idx * 60 * 60 * 1000).toISOString(),
            endTime: null,
            worker: wo.assignees[idx % wo.assignees.length],
          };
        }
      });

      return {
        ...wo,
        stepStatus: updatedStepStatus,
        currentStep: steps[completedSteps] || steps[steps.length - 1],
        status: '진행중',
        completedQty: Math.floor(wo.totalQty * 0.5),
      };
    });

    results.data.workOrders = updatedWorkOrders;
    logStep('작업진행중', '작업단계 진행 상태 업데이트 완료');

    // ─────────────────────────────────────────────────────────
    // STEP 5: 중간검사 (PQC)
    // ─────────────────────────────────────────────────────────
    logStep('중간검사', '공정별 중간검사 수행');

    const inspections = [];
    updatedWorkOrders.forEach(wo => {
      const inspection = createInspectionFromWorkOrder(wo, 'PQC');
      inspection.status = '검사완료';
      inspection.result = '합격';
      inspection.passQty = wo.totalQty;
      inspection.failQty = 0;
      inspection.inspectorName = '김검사';
      inspection.checkItems = inspection.checkItems.map(item => ({
        ...item,
        result: '합격',
        status: '검사완료',
      }));
      inspections.push(inspection);
    });

    results.data.inspections = inspections;
    logStep('중간검사완료', `${inspections.length}건 검사 완료 (전량 합격)`, inspections.map(ins => ({
      inspectionNo: ins.inspectionNo,
      result: ins.result,
    })));

    // ─────────────────────────────────────────────────────────
    // STEP 6: 작업완료 (전체 단계 완료 처리)
    // ─────────────────────────────────────────────────────────
    logStep('작업완료', '전체 작업 완료 처리');

    const completedWorkOrders = updatedWorkOrders.map(wo => {
      const steps = Object.keys(wo.stepStatus);
      const completedStepStatus = { ...wo.stepStatus };

      steps.forEach((step, idx) => {
        completedStepStatus[step] = {
          status: '완료',
          startTime: new Date(today.getTime() + idx * 60 * 60 * 1000).toISOString(),
          endTime: new Date(today.getTime() + (idx + 1) * 60 * 60 * 1000).toISOString(),
          worker: wo.assignees[idx % wo.assignees.length],
        };
      });

      return {
        ...wo,
        stepStatus: completedStepStatus,
        currentStep: '완료',
        status: '생산완료',
        completedQty: wo.totalQty,
        defectQty: 0,
      };
    });

    results.data.workOrders = completedWorkOrders;
    logStep('작업완료처리', '모든 공정 작업 완료');

    // ─────────────────────────────────────────────────────────
    // STEP 7: 최종검사 (FQC)
    // ─────────────────────────────────────────────────────────
    logStep('최종검사', '최종 품질검사 수행');

    const finalInspection = createInspectionFromWorkOrder(completedWorkOrders[0], 'FQC');
    finalInspection.status = '검사완료';
    finalInspection.result = '합격';
    finalInspection.passQty = order.totalQty;
    finalInspection.failQty = 0;
    finalInspection.inspectorName = '박품질';
    finalInspection.checkItems = finalInspection.checkItems.map(item => ({
      ...item,
      result: '합격',
      status: '검사완료',
    }));

    results.data.finalInspection = finalInspection;
    logStep('최종검사완료', `최종검사 ${finalInspection.result}`, { inspectionNo: finalInspection.inspectionNo, result: finalInspection.result });

    // ─────────────────────────────────────────────────────────
    // STEP 8: 입금 확인 (회계연동)
    // ─────────────────────────────────────────────────────────
    logStep('입금확인', '선수금/계약금 입금 확인');

    const deposit = {
      id: Date.now() + 100,
      depositNo: `DEP-${today.toISOString().split('T')[0].replace(/-/g, '')}-${String(testNo).padStart(2, '0')}`,
      orderId: order.id,
      orderNo: order.orderNo,
      customerId: customer.id,
      customerName: customer.customerName,
      depositType: '계약금',
      depositAmount: Math.floor(order.totalAmount * 0.3), // 30% 계약금
      depositDate: today.toISOString().split('T')[0],
      bankName: '우리은행',
      accountNo: '1005-XXX-XXXXXX',
      depositor: customer.customerName,
      status: '입금완료',
      note: '계약금 30% 입금',
    };

    results.data.deposit = deposit;
    logStep('입금완료', `계약금 ${deposit.depositAmount.toLocaleString()}원 입금 확인`, { depositNo: deposit.depositNo, amount: deposit.depositAmount });

    // ─────────────────────────────────────────────────────────
    // STEP 9: 출하 처리
    // ─────────────────────────────────────────────────────────
    logStep('출하처리', '출하 지시 및 배송');

    const shipment = createShipmentFromInspection(completedWorkOrders[0], finalInspection);
    shipment.status = '출하완료';
    shipment.deliveryType = '직배송';
    shipment.vehicleNo = '12가3456';
    shipment.driverName = '이배송';
    shipment.deliveryDate = today.toISOString().split('T')[0];
    shipment.receiverName = site.siteManager;
    shipment.receiverPhone = site.managerPhone;
    shipment.deliveryAddress = site.address;

    results.data.shipment = shipment;
    logStep('출하완료', `출하번호: ${shipment.shipmentNo}, 배송지: ${site.siteName}`, { shipmentNo: shipment.shipmentNo, deliveryAddress: site.address });

    // ─────────────────────────────────────────────────────────
    // STEP 10: 잔금 청구 및 매출 확정
    // ─────────────────────────────────────────────────────────
    logStep('매출확정', '잔금 청구 및 매출 확정');

    const sales = {
      id: Date.now() + 200,
      salesNo: generateDocumentNumber('SL', today),
      orderId: order.id,
      orderNo: order.orderNo,
      shipmentId: shipment.id,
      shipmentNo: shipment.shipmentNo,
      customerId: customer.id,
      customerName: customer.customerName,
      siteId: site.id,
      siteName: site.siteName,
      salesDate: today.toISOString().split('T')[0],
      supplyAmount: Math.floor(order.totalAmount / 1.1),
      vatAmount: Math.floor(order.totalAmount - order.totalAmount / 1.1),
      totalAmount: order.totalAmount,
      depositAmount: deposit.depositAmount,
      remainingAmount: order.totalAmount - deposit.depositAmount,
      status: '청구완료',
      invoiceDate: today.toISOString().split('T')[0],
    };

    results.data.sales = sales;
    logStep('매출확정완료', `매출번호: ${sales.salesNo}, 잔금: ${sales.remainingAmount.toLocaleString()}원`, { salesNo: sales.salesNo, remainingAmount: sales.remainingAmount });

    // 결과 요약
    results.summary = {
      quoteNo: quote.quoteNo,
      orderNo: order.orderNo,
      workOrderCount: completedWorkOrders.length,
      workOrderNos: completedWorkOrders.map(wo => wo.workOrderNo),
      inspectionCount: inspections.length + 1,
      shipmentNo: shipment.shipmentNo,
      salesNo: sales.salesNo,
      totalAmount: order.totalAmount,
      depositAmount: deposit.depositAmount,
      remainingAmount: sales.remainingAmount,
      processFlow: '견적→수주→작업지시→작업진행→중간검사→작업완료→최종검사→입금→출하→매출확정',
    };

    logStep('테스트완료', `전체 프로세스 테스트 성공!`, results.summary);

  } catch (error) {
    results.success = false;
    results.errors.push({
      step: results.timeline[results.timeline.length - 1]?.step || 'unknown',
      error: error.message,
      stack: error.stack,
    });
    console.error(`[테스트 #${testNo}] 오류 발생:`, error);
  }

  return results;
};

/**
 * 5개 전체 통합 테스트 실행
 */
export const runAllIntegrationTests = () => {
  console.log('═══════════════════════════════════════════════════════════════');
  console.log('  MES 전체 시스템 통합 테스트 시작');
  console.log('  기준정보 → 견적 → 수주 → 생산 → 검사 → 출하 전체 연동 검증');
  console.log('═══════════════════════════════════════════════════════════════');

  const testCases = [
    {
      customer: testCustomers[0],
      site: testSites[0],
      product: testProducts[0],
      openWidth: 3000,
      openHeight: 3000,
      productType: '스크린',
      qty: 2
    },
    {
      customer: testCustomers[1],
      site: testSites[1],
      product: testProducts[1],
      openWidth: 3500,
      openHeight: 4000,
      productType: '스크린',
      qty: 3
    },
    {
      customer: testCustomers[2],
      site: testSites[2],
      product: testProducts[2],
      openWidth: 2500,
      openHeight: 3000,
      productType: '철재',
      qty: 1
    },
    {
      customer: testCustomers[3],
      site: testSites[3],
      product: testProducts[3],
      openWidth: 4000,
      openHeight: 4500,
      productType: '스크린',
      qty: 4
    },
    {
      customer: testCustomers[4],
      site: testSites[4],
      product: testProducts[4],
      openWidth: 3000,
      openHeight: 3500,
      productType: '철재',
      qty: 2
    },
  ];

  const results = [];

  testCases.forEach((testCase, index) => {
    console.log(`\n─── 테스트 #${index + 1} 시작 ───`);
    const result = runFullProcessTest({ ...testCase, testNo: index + 1 });
    results.push(result);
  });

  // 결과 요약
  const summary = {
    totalTests: results.length,
    successCount: results.filter(r => r.success).length,
    failCount: results.filter(r => !r.success).length,
    results: results.map(r => ({
      testNo: r.testNo,
      testName: r.testName,
      success: r.success,
      summary: r.summary,
      errors: r.errors,
    })),
  };

  console.log('\n═══════════════════════════════════════════════════════════════');
  console.log('  통합 테스트 결과 요약');
  console.log('═══════════════════════════════════════════════════════════════');
  console.log(`  총 테스트: ${summary.totalTests}건`);
  console.log(`  성공: ${summary.successCount}건`);
  console.log(`  실패: ${summary.failCount}건`);
  console.log('───────────────────────────────────────────────────────────────');

  results.forEach(r => {
    console.log(`  [${r.success ? '✅' : '❌'}] ${r.testName}`);
    if (r.summary) {
      console.log(`      견적: ${r.summary.quoteNo} → 수주: ${r.summary.orderNo}`);
      console.log(`      작업지시: ${r.summary.workOrderNos?.join(', ')}`);
      console.log(`      출하: ${r.summary.shipmentNo} → 매출: ${r.summary.salesNo}`);
    }
  });

  return { results, summary };
};

/**
 * 전체 마스터 데이터 내보내기
 */
export const getAllMasterData = () => ({
  customers: testCustomers,
  sites: testSites,
  products: testProducts,
  parts: testParts,
  rawMaterials: testRawMaterials,
  consumables: testConsumables,
});

export default {
  // 마스터 데이터
  testCustomers,
  testSites,
  testProducts,
  testParts,
  testRawMaterials,
  testConsumables,
  getAllMasterData,
  // 테스트 함수
  runFullProcessTest,
  runAllIntegrationTests,
};
