// ============================================================
// 시스템 정책서 설정 (Policy Configuration)
// 모든 업무 규칙, 상태값, 연동 정책을 통합 관리
// ============================================================

// ============ 1. 문서 상태 정책 ============
export const documentStatusPolicy = {
  // 견적서 상태 흐름
  quote: {
    name: '견적서',
    statuses: [
      { code: 'DRAFT', label: '작성중', color: 'gray', description: '견적서 초안 작성 중' },
      { code: 'SUBMITTED', label: '제출', color: 'blue', description: '고객에게 견적서 제출됨' },
      { code: 'APPROVED', label: '승인', color: 'green', description: '고객이 견적을 승인함' },
      { code: 'REJECTED', label: '반려', color: 'red', description: '고객이 견적을 거절함' },
      { code: 'EXPIRED', label: '만료', color: 'gray', description: '견적 유효기간 초과' },
      { code: 'CONVERTED', label: '수주전환', color: 'purple', description: '수주로 전환됨' },
    ],
    transitions: [
      { from: 'DRAFT', to: 'SUBMITTED', action: '제출', requiredFields: ['customerCode', 'items', 'validUntil'] },
      { from: 'SUBMITTED', to: 'APPROVED', action: '승인', requiredFields: [] },
      { from: 'SUBMITTED', to: 'REJECTED', action: '반려', requiredFields: ['rejectReason'] },
      { from: 'APPROVED', to: 'CONVERTED', action: '수주전환', createsDocument: 'order' },
      { from: 'SUBMITTED', to: 'EXPIRED', action: '만료', autoTrigger: 'validUntil < today' },
    ],
    validityDays: 30,
    numberingRule: 'QT-{YYYY}{MM}-{SEQ:4}',
  },

  // 수주 상태 흐름
  order: {
    name: '수주',
    statuses: [
      { code: 'REGISTERED', label: '등록', color: 'gray', description: '수주 등록됨' },
      { code: 'CONFIRMED', label: '확정', color: 'blue', description: '수주 확정 (생산지시 가능)' },
      { code: 'IN_PRODUCTION', label: '생산중', color: 'orange', description: '생산 진행 중' },
      { code: 'PRODUCTION_COMPLETE', label: '생산완료', color: 'green', description: '모든 생산 완료' },
      { code: 'SHIPPING', label: '출하중', color: 'purple', description: '출하 진행 중' },
      { code: 'SHIPPED', label: '출하완료', color: 'blue', description: '출하 완료' },
      { code: 'COMPLETED', label: '완료', color: 'green', description: '수주 완료 (정산 완료)' },
      { code: 'CANCELLED', label: '취소', color: 'red', description: '수주 취소됨' },
    ],
    transitions: [
      { from: 'REGISTERED', to: 'CONFIRMED', action: '확정', requiredFields: ['deliveryDate', 'siteCode'] },
      { from: 'CONFIRMED', to: 'IN_PRODUCTION', action: '생산시작', createsDocument: 'productionOrder' },
      { from: 'IN_PRODUCTION', to: 'PRODUCTION_COMPLETE', action: '생산완료', autoTrigger: 'allWorkOrdersComplete' },
      { from: 'PRODUCTION_COMPLETE', to: 'SHIPPING', action: '출하시작', createsDocument: 'shipment' },
      { from: 'SHIPPING', to: 'SHIPPED', action: '출하완료', autoTrigger: 'allShipmentsComplete' },
      { from: 'SHIPPED', to: 'COMPLETED', action: '완료처리', requiredFields: ['billingComplete'] },
      { from: 'REGISTERED', to: 'CANCELLED', action: '취소', requiredFields: ['cancelReason'] },
      { from: 'CONFIRMED', to: 'CANCELLED', action: '취소', requiredFields: ['cancelReason', 'approvalRequired'] },
    ],
    numberingRule: 'SO-{YYYY}{MM}-{SEQ:4}',
  },

  // 생산지시 상태 흐름
  productionOrder: {
    name: '생산지시',
    statuses: [
      { code: 'PLANNED', label: '계획', color: 'gray', description: '생산 계획 수립됨' },
      { code: 'RELEASED', label: '지시', color: 'blue', description: '작업지시 발행됨' },
      { code: 'IN_PROGRESS', label: '진행중', color: 'orange', description: '생산 진행 중' },
      { code: 'COMPLETED', label: '완료', color: 'green', description: '생산 완료' },
      { code: 'CANCELLED', label: '취소', color: 'red', description: '생산지시 취소' },
    ],
    transitions: [
      { from: 'PLANNED', to: 'RELEASED', action: '지시발행', createsDocument: 'workOrder' },
      { from: 'RELEASED', to: 'IN_PROGRESS', action: '작업시작', autoTrigger: 'firstWorkOrderStarted' },
      { from: 'IN_PROGRESS', to: 'COMPLETED', action: '완료', autoTrigger: 'allWorkOrdersComplete' },
      { from: 'PLANNED', to: 'CANCELLED', action: '취소', requiredFields: ['cancelReason'] },
    ],
    numberingRule: 'PO-{YYYY}{MM}-{SEQ:4}',
  },

  // 작업지시 상태 흐름
  workOrder: {
    name: '작업지시',
    statuses: [
      { code: 'WAITING', label: '대기', color: 'gray', description: '작업 대기 중' },
      { code: 'IN_PROGRESS', label: '진행중', color: 'orange', description: '작업 진행 중' },
      { code: 'PAUSED', label: '일시정지', color: 'yellow', description: '작업 일시 정지' },
      { code: 'COMPLETED', label: '완료', color: 'green', description: '작업 완료' },
      { code: 'CANCELLED', label: '취소', color: 'red', description: '작업 취소' },
    ],
    transitions: [
      { from: 'WAITING', to: 'IN_PROGRESS', action: '작업시작', requiredFields: ['workerId', 'startTime'] },
      { from: 'IN_PROGRESS', to: 'PAUSED', action: '일시정지', requiredFields: ['pauseReason'] },
      { from: 'PAUSED', to: 'IN_PROGRESS', action: '작업재개', requiredFields: [] },
      { from: 'IN_PROGRESS', to: 'COMPLETED', action: '완료', createsDocument: 'workResult', requiredFields: ['actualQty'] },
      { from: 'WAITING', to: 'CANCELLED', action: '취소', requiredFields: ['cancelReason'] },
    ],
    numberingRule: 'WO-{YYYY}{MM}{DD}-{SEQ:4}',
  },

  // 출하 상태 흐름
  shipment: {
    name: '출하',
    statuses: [
      { code: 'PLANNED', label: '예정', color: 'gray', description: '출하 예정' },
      { code: 'PICKING', label: '피킹중', color: 'blue', description: '출하 피킹 진행' },
      { code: 'PACKED', label: '포장완료', color: 'purple', description: '포장 완료' },
      { code: 'SHIPPING', label: '배송중', color: 'orange', description: '배송 진행 중' },
      { code: 'DELIVERED', label: '배송완료', color: 'green', description: '배송 완료' },
      { code: 'CANCELLED', label: '취소', color: 'red', description: '출하 취소' },
    ],
    transitions: [
      { from: 'PLANNED', to: 'PICKING', action: '피킹시작', requiredFields: [] },
      { from: 'PICKING', to: 'PACKED', action: '포장완료', requiredFields: ['packageCount', 'totalWeight'] },
      { from: 'PACKED', to: 'SHIPPING', action: '배송시작', requiredFields: ['vehicleNo', 'driverName'] },
      { from: 'SHIPPING', to: 'DELIVERED', action: '배송완료', requiredFields: ['deliveryConfirmation'] },
      { from: 'PLANNED', to: 'CANCELLED', action: '취소', requiredFields: ['cancelReason'] },
    ],
    numberingRule: 'SH-{YYYY}{MM}{DD}-{SEQ:3}',
  },

  // 검사 상태 흐름
  inspection: {
    name: '검사',
    statuses: [
      { code: 'PENDING', label: '대기', color: 'gray', description: '검사 대기' },
      { code: 'IN_PROGRESS', label: '검사중', color: 'orange', description: '검사 진행 중' },
      { code: 'PASSED', label: '합격', color: 'green', description: '검사 합격' },
      { code: 'FAILED', label: '불합격', color: 'red', description: '검사 불합격' },
      { code: 'REWORK', label: '재작업', color: 'yellow', description: '재작업 진행' },
      { code: 'REWORK_COMPLETE', label: '재작업완료', color: 'blue', description: '재작업 후 재검사 대기' },
    ],
    transitions: [
      { from: 'PENDING', to: 'IN_PROGRESS', action: '검사시작', requiredFields: ['inspectorId'] },
      { from: 'IN_PROGRESS', to: 'PASSED', action: '합격처리', requiredFields: ['checkResults'] },
      { from: 'IN_PROGRESS', to: 'FAILED', action: '불합격처리', requiredFields: ['defectReason', 'checkResults'] },
      { from: 'FAILED', to: 'REWORK', action: '재작업지시', createsDocument: 'reworkOrder' },
      { from: 'REWORK', to: 'REWORK_COMPLETE', action: '재작업완료', requiredFields: [] },
      { from: 'REWORK_COMPLETE', to: 'PENDING', action: '재검사요청', requiredFields: [] },
    ],
    types: {
      IQC: { name: '수입검사', description: '자재 입고 시 품질 검사', timing: '입고 시' },
      PQC: { name: '중간검사', description: '생산 공정 중 품질 검사', timing: '공정 중' },
      FQC: { name: '제품검사', description: '완제품 최종 품질 검사', timing: '포장 전' },
    },
  },
};

// ============ 2. 문서 연동 정책 ============
export const documentLinkagePolicy = {
  // 문서 간 연결 관계
  relationships: [
    {
      parent: 'quote',
      child: 'order',
      relationship: '1:1',
      linkField: 'quoteId',
      inheritFields: ['customerId', 'siteId', 'items', 'totalAmount'],
      description: '견적서 승인 시 수주로 전환',
    },
    {
      parent: 'order',
      child: 'productionOrder',
      relationship: '1:N',
      linkField: 'orderId',
      inheritFields: ['items', 'deliveryDate', 'siteId'],
      description: '수주 확정 시 생산지시 생성 (품목별 분할 가능)',
    },
    {
      parent: 'productionOrder',
      child: 'workOrder',
      relationship: '1:N',
      linkField: 'productionOrderId',
      inheritFields: ['productId', 'qty', 'deliveryDate'],
      description: '생산지시 발행 시 공정별 작업지시 생성',
    },
    {
      parent: 'workOrder',
      child: 'workResult',
      relationship: '1:1',
      linkField: 'workOrderId',
      inheritFields: ['productId', 'plannedQty', 'stepCode'],
      description: '작업지시 완료 시 작업실적 생성',
    },
    {
      parent: 'workOrder',
      child: 'inspection',
      relationship: '1:N',
      linkField: 'workOrderId',
      inheritFields: ['productId', 'qty', 'stepCode'],
      description: 'QC 공정에서 검사 레코드 생성',
    },
    {
      parent: 'order',
      child: 'shipment',
      relationship: '1:N',
      linkField: 'orderId',
      inheritFields: ['customerId', 'siteId', 'items', 'deliveryDate'],
      description: '생산완료 시 출하 생성 (분할 출하 가능)',
    },
  ],

  // 상태 연동 규칙
  statusSync: [
    {
      trigger: { document: 'workOrder', status: 'COMPLETED' },
      updates: [
        { document: 'productionOrder', condition: 'allWorkOrdersComplete', newStatus: 'COMPLETED' },
      ],
    },
    {
      trigger: { document: 'productionOrder', status: 'COMPLETED' },
      updates: [
        { document: 'order', condition: 'allProductionOrdersComplete', newStatus: 'PRODUCTION_COMPLETE' },
      ],
    },
    {
      trigger: { document: 'shipment', status: 'DELIVERED' },
      updates: [
        { document: 'order', condition: 'allShipmentsDelivered', newStatus: 'SHIPPED' },
      ],
    },
    {
      trigger: { document: 'inspection', status: 'FAILED' },
      updates: [
        { document: 'workOrder', newStatus: 'PAUSED', requiresAction: 'rework_decision' },
      ],
    },
  ],
};

// ============ 3. 공정 흐름 정책 ============
export const processFlowPolicy = {
  // 공정 유형별 정의
  workflows: {
    SCREEN: {
      name: '스크린 공정',
      steps: ['SCR-MAT', 'SCR-CUT', 'SCR-SEW', 'SCR-QC1', 'SCR-PACK'],
      description: '스크린 제품 생산 공정',
      estimatedDays: 3,
    },
    SLAT: {
      name: '슬랫 공정',
      steps: ['SLT-CUT', 'SLT-FIN', 'SLT-QC1', 'SLT-PACK'],
      description: '슬랫 제품 생산 공정',
      estimatedDays: 2,
    },
    FOLD: {
      name: '절곡 공정',
      steps: ['FLD-MAT', 'FLD-CUT', 'FLD-BEND', 'FLD-WLD', 'FLD-QC1', 'FLD-PACK'],
      description: '절곡 부품 생산 공정',
      estimatedDays: 4,
    },
    STOCK: {
      name: '샤프트 공정',
      steps: ['STK-MAT', 'STK-CUT', 'STK-MCH', 'STK-QC1', 'STK-PACK'],
      description: '샤프트 가공 공정',
      estimatedDays: 3,
    },
  },

  // 공정 합류점 정책
  mergePoints: {
    PACK: {
      name: '포장 합류점',
      description: '모든 공정의 PACK 단계가 완료되면 최종 포장 진행',
      requiredWorkflows: ['SCREEN', 'SLAT', 'FOLD', 'STOCK'],
      outputDocument: 'packaging',
    },
    ASSEMBLY: {
      name: '조립 합류점',
      description: '구성품 조립을 위한 합류점',
      requiredWorkflows: ['SCREEN', 'SLAT'],
      outputDocument: 'assemblyOrder',
    },
  },

  // 공정 순서 제약
  sequenceConstraints: [
    { workflow: 'SCREEN', rule: 'MAT → CUT → SEW → QC → PACK', description: '순차 실행 필수' },
    { workflow: 'FOLD', rule: 'CUT || BEND → WLD → QC → PACK', description: 'CUT과 BEND 병렬 가능' },
  ],
};

// ============ 4. 자재 정책 ============
export const materialPolicy = {
  // LOT 관리 정책
  lotManagement: {
    trackingRequired: ['원자재', '부자재', '구매부품'],
    lotNumberFormat: '{PRODUCT}-{TYPE}-{YYMMDD}-{SIZE}',
    expiryManagement: true,
    fifoEnforced: true,
  },

  // 재고 정책
  inventoryPolicy: {
    safetyStockLevel: 'MIN_STOCK',
    reorderPoint: 'SAFETY_STOCK * 1.5',
    maxStockLevel: 'REORDER_POINT * 3',
    stockLocations: ['창고A', '창고B', '생산라인', '출하대기'],
  },

  // 입출고 정책
  transactionPolicy: {
    inbound: {
      types: ['구매입고', '생산입고', '반품입고', '이동입고', '재고조정입고'],
      requiresInspection: ['구매입고'],
      requiresLotAssignment: ['구매입고', '생산입고'],
    },
    outbound: {
      types: ['생산출고', '판매출고', '반품출고', '이동출고', '재고조정출고', '폐기'],
      requiresApproval: ['폐기', '재고조정출고'],
      lotSelectionMethod: 'FIFO',
    },
  },
};

// ============ 5. 단가 정책 ============
export const pricingPolicy = {
  // 단가 계산 공식
  calculation: {
    costPrice: '매입단가 + 가공비',
    lossAppliedCost: '원가 × (1 + LOSS율/100)',
    sellingPrice: '원가(LOSS적용) × (1 + 마진율/100)',
    marginAmount: '판매단가 - 원가(LOSS적용)',
  },

  // 거래처 그룹별 할인 정책
  customerGroupDiscount: {
    VIP: { discountRate: 10, criteria: '연간 거래액 1억 이상' },
    GOLD: { discountRate: 7, criteria: '연간 거래액 5천만원 이상' },
    SILVER: { discountRate: 5, criteria: '연간 거래액 1천만원 이상' },
    NORMAL: { discountRate: 0, criteria: '일반 거래 고객' },
  },

  // 단가 이력 정책
  historyPolicy: {
    trackChanges: true,
    retentionPeriod: '5년',
    changeReasonRequired: true,
    approvalRequired: 'marginRate < 15',
  },

  // 자동 재계산 조건
  autoRecalculation: {
    triggers: ['매입단가 변경', '가공비 변경', 'LOSS율 변경', '마진율 변경'],
    notifyOnChange: true,
  },
};

// ============ 6. 품목코드 정책 ============
export const itemCodePolicy = {
  // 품목유형별 코드 체계
  patterns: {
    제품: {
      format: 'FG-{CATEGORY}-{TYPE}-{SEQ:3}',
      example: 'FG-SCR-STD-001',
      description: 'FG=완제품, CATEGORY=품목분류, TYPE=제품유형',
    },
    부품_조립: {
      format: 'PT-ASY-{PART}-{SEQ:3}',
      example: 'PT-ASY-SFT4-001',
      description: 'PT=부품, ASY=조립품, PART=부품유형',
    },
    부품_절곡: {
      format: 'PT-BND-{PART}-{SEQ:3}',
      example: 'PT-BND-R-001',
      description: 'PT=부품, BND=절곡품, PART=부품코드',
    },
    부품_구매: {
      format: '{CODE}-{POWER}-{CAPACITY}',
      example: 'E-220V-300 KG',
      description: '구매품 고유 코드 체계',
    },
    부자재: {
      format: '{CODE}-{SPEC}',
      example: 'SCR-0.3T',
      description: '부자재 코드-규격',
    },
    원자재: {
      format: '{MATERIAL}-{SPEC}',
      example: 'STEEL-1.2T',
      description: '원자재명-두께/규격',
    },
    소모품: {
      format: '{NAME}-{SPEC}',
      example: '볼트-M8×20',
      description: '품명-규격',
    },
  },

  // LOT 번호 체계
  lotNumberPattern: {
    format: '{PRODUCT}-{TYPE}-{YYMDD}-{SIZE}',
    example: 'G-I-4A05-53',
    components: {
      PRODUCT: '제품코드 (G=연기차단재)',
      TYPE: '종류코드 (I=화이바원단)',
      YYMDD: '년(1자리)월(1자리)일(2자리)',
      SIZE: '모양&길이 코드',
    },
  },
};

// ============ 7. 권한 정책 ============
export const authorizationPolicy = {
  roles: {
    ADMIN: {
      name: '시스템관리자',
      permissions: ['*'],
      description: '모든 기능 접근 가능',
    },
    SALES_MANAGER: {
      name: '영업관리자',
      permissions: ['quote.*', 'order.*', 'customer.*', 'site.*', 'price.read'],
      description: '영업 관련 전체 권한',
    },
    PRODUCTION_MANAGER: {
      name: '생산관리자',
      permissions: ['productionOrder.*', 'workOrder.*', 'workResult.*', 'item.read', 'order.read'],
      description: '생산 관련 전체 권한',
    },
    QUALITY_MANAGER: {
      name: '품질관리자',
      permissions: ['inspection.*', 'defect.*', 'workOrder.read', 'item.read'],
      description: '품질 관련 전체 권한',
    },
    WORKER: {
      name: '작업자',
      permissions: ['workOrder.read', 'workResult.create', 'workResult.update'],
      description: '작업 실행 권한',
    },
    VIEWER: {
      name: '조회자',
      permissions: ['*.read'],
      description: '전체 조회 권한',
    },
  },

  // 문서별 결재 정책
  approvalPolicy: {
    quote: { amount: 50000000, approvers: ['SALES_MANAGER'] },
    order: { amount: 100000000, approvers: ['SALES_MANAGER', 'ADMIN'] },
    shipment: { always: true, approvers: ['SALES_MANAGER'] },
    priceChange: { marginBelow: 15, approvers: ['SALES_MANAGER', 'ADMIN'] },
  },
};

// ============ 8. 용어 정의 ============
export const terminologyPolicy = {
  documents: {
    quote: { korean: '견적서', abbreviation: 'QT', description: '고객에게 제출하는 가격 제안서' },
    order: { korean: '수주', abbreviation: 'SO', description: '확정된 주문' },
    productionOrder: { korean: '생산지시', abbreviation: 'PO', description: '생산을 위한 지시서' },
    workOrder: { korean: '작업지시', abbreviation: 'WO', description: '개별 공정 작업 지시' },
    workResult: { korean: '작업실적', abbreviation: 'WR', description: '작업 완료 실적' },
    shipment: { korean: '출하', abbreviation: 'SH', description: '제품 출하 문서' },
    inspection: { korean: '검사', abbreviation: 'INS', description: '품질 검사 기록' },
  },

  itemTypes: {
    product: { korean: '제품', description: '최종 판매 제품' },
    part: { korean: '부품', description: '제품 구성 부품' },
    subMaterial: { korean: '부자재', description: '생산 보조 자재' },
    rawMaterial: { korean: '원자재', description: '가공 전 원재료' },
    consumable: { korean: '소모품', description: '소모성 자재' },
  },

  processes: {
    SCR: { korean: '스크린', description: '스크린 생산 공정' },
    SLT: { korean: '슬랫', description: '슬랫 생산 공정' },
    FLD: { korean: '절곡', description: '절곡 가공 공정' },
    STK: { korean: '샤프트', description: '샤프트 가공 공정' },
  },

  inspectionTypes: {
    IQC: { korean: '수입검사', fullName: 'Incoming Quality Control' },
    PQC: { korean: '중간검사', fullName: 'Process Quality Control' },
    FQC: { korean: '제품검사', fullName: 'Final Quality Control' },
  },
};

// ============ 9. 알림 정책 ============
export const notificationPolicy = {
  events: [
    { event: 'quote.submitted', recipients: ['customer'], channel: ['email'], template: 'quote_submitted' },
    { event: 'order.confirmed', recipients: ['production_manager'], channel: ['system'], template: 'order_confirmed' },
    { event: 'inspection.failed', recipients: ['quality_manager', 'production_manager'], channel: ['system', 'email'], template: 'inspection_failed' },
    { event: 'shipment.delivered', recipients: ['sales_manager', 'customer'], channel: ['email'], template: 'shipment_delivered' },
    { event: 'inventory.lowStock', recipients: ['inventory_manager'], channel: ['system'], template: 'low_stock_alert' },
  ],
};

// ============ 정책 통합 조회 함수 ============
export const getPolicyByCategory = (category) => {
  const policies = {
    documentStatus: documentStatusPolicy,
    documentLinkage: documentLinkagePolicy,
    processFlow: processFlowPolicy,
    material: materialPolicy,
    pricing: pricingPolicy,
    itemCode: itemCodePolicy,
    authorization: authorizationPolicy,
    terminology: terminologyPolicy,
    notification: notificationPolicy,
  };
  return policies[category] || null;
};

export const getAllPolicies = () => ({
  documentStatus: documentStatusPolicy,
  documentLinkage: documentLinkagePolicy,
  processFlow: processFlowPolicy,
  material: materialPolicy,
  pricing: pricingPolicy,
  itemCode: itemCodePolicy,
  authorization: authorizationPolicy,
  terminology: terminologyPolicy,
  notification: notificationPolicy,
});

export default {
  documentStatusPolicy,
  documentLinkagePolicy,
  processFlowPolicy,
  materialPolicy,
  pricingPolicy,
  itemCodePolicy,
  authorizationPolicy,
  terminologyPolicy,
  notificationPolicy,
  getPolicyByCategory,
  getAllPolicies,
};
