/**
 * 산업별 섹션 프리셋
 * 백엔드 DB에 저장할 section config의 프론트엔드 프리셋 정의
 *
 * 사용: 관리자가 페이지 구조 설계 시 프리셋 선택 → properties JSON으로 저장
 * 확장: 새 산업/섹션 = 이 파일에 객체 추가
 */

import type { TableConfig } from '../types';

export interface SectionPreset {
  id: string;
  name: string;
  description: string;
  industry: string;
  sectionType: 'fields' | 'table';
  tableConfig?: TableConfig;
  fields?: Array<{
    field_key: string;
    field_name: string;
    field_type: string;
    options?: Array<{ label: string; value: string }>;
    properties?: Record<string, unknown>;
    is_required?: boolean;
  }>;
}

// ============================================
// 제조업 프리셋
// ============================================

export const MANUFACTURING_PROCESS_TABLE: SectionPreset = {
  id: 'mfg-process',
  name: '공정 정보',
  description: '제조 공정 순서 및 상세 정보',
  industry: '제조',
  sectionType: 'table',
  tableConfig: {
    columns: [
      { key: 'process_name', label: '공정명', fieldType: 'reference', width: '150px', isRequired: true, properties: { source: 'processes' } },
      { key: 'equipment', label: '설비', fieldType: 'reference', width: '130px', properties: { source: 'equipment' } },
      { key: 'cycle_time', label: '사이클타임(초)', fieldType: 'number', width: '100px' },
      { key: 'setup_time', label: '셋업시간(분)', fieldType: 'number', width: '100px' },
      { key: 'note', label: '비고', fieldType: 'textbox' },
    ],
    minRows: 1,
    maxRows: 30,
    summaryRow: [
      { columnKey: 'cycle_time', type: 'sum' },
      { columnKey: 'setup_time', type: 'sum' },
    ],
  },
};

export const MANUFACTURING_QC_TABLE: SectionPreset = {
  id: 'mfg-qc',
  name: '품질검사 항목',
  description: '검사 항목 및 기준값',
  industry: '제조',
  sectionType: 'table',
  tableConfig: {
    columns: [
      { key: 'inspection_item', label: '검사항목', fieldType: 'textbox', width: '150px', isRequired: true },
      { key: 'method', label: '검사방법', fieldType: 'dropdown', width: '120px', options: [
        { label: '육안검사', value: 'visual' },
        { label: '치수검사', value: 'dimension' },
        { label: '기능검사', value: 'functional' },
        { label: '파괴검사', value: 'destructive' },
      ]},
      { key: 'standard_value', label: '기준값', fieldType: 'textbox', width: '100px' },
      { key: 'tolerance_min', label: '하한', fieldType: 'number', width: '80px' },
      { key: 'tolerance_max', label: '상한', fieldType: 'number', width: '80px' },
      { key: 'unit', label: '단위', fieldType: 'textbox', width: '60px' },
    ],
    minRows: 1,
    maxRows: 50,
  },
};

export const MANUFACTURING_VENDOR_TABLE: SectionPreset = {
  id: 'mfg-vendor',
  name: '구매처 정보',
  description: '원자재/부품 구매처 목록',
  industry: '제조',
  sectionType: 'table',
  tableConfig: {
    columns: [
      { key: 'vendor', label: '거래처', fieldType: 'reference', width: '150px', isRequired: true, properties: { source: 'vendors' } },
      { key: 'unit_price', label: '단가', fieldType: 'number', width: '100px' },
      { key: 'lead_time', label: '리드타임(일)', fieldType: 'number', width: '90px' },
      { key: 'is_primary', label: '주거래처', fieldType: 'checkbox', width: '80px' },
      { key: 'note', label: '비고', fieldType: 'textbox' },
    ],
    maxRows: 10,
  },
};

// ============================================
// 건설/공사업 프리셋
// ============================================

export const CONSTRUCTION_SPEC_FIELDS: SectionPreset = {
  id: 'const-spec',
  name: '시방 정보',
  description: '자재 시방 및 규격 상세',
  industry: '건설',
  sectionType: 'fields',
  fields: [
    { field_key: 'material_grade', field_name: '자재 등급', field_type: 'dropdown', options: [
      { label: 'SS400', value: 'SS400' },
      { label: 'STS304', value: 'STS304' },
      { label: 'STS316', value: 'STS316' },
      { label: 'AL6061', value: 'AL6061' },
    ]},
    { field_key: 'surface_treatment', field_name: '표면처리', field_type: 'dropdown', options: [
      { label: '무처리', value: 'none' },
      { label: '도금', value: 'plating' },
      { label: '도장', value: 'painting' },
      { label: '아노다이징', value: 'anodizing' },
    ]},
    { field_key: 'fire_rating', field_name: '내화등급', field_type: 'textbox' },
    { field_key: 'installation_site', field_name: '설치현장', field_type: 'reference', properties: { source: 'sites' } },
  ],
};

export const CONSTRUCTION_SCHEDULE_TABLE: SectionPreset = {
  id: 'const-schedule',
  name: '공정표',
  description: '시공 일정 및 공정 정보',
  industry: '건설',
  sectionType: 'table',
  tableConfig: {
    columns: [
      { key: 'work_name', label: '작업명', fieldType: 'textbox', width: '150px', isRequired: true },
      { key: 'start_date', label: '시작일', fieldType: 'date', width: '120px' },
      { key: 'end_date', label: '종료일', fieldType: 'date', width: '120px' },
      { key: 'worker_count', label: '작업인원', fieldType: 'number', width: '80px' },
      { key: 'status', label: '상태', fieldType: 'dropdown', width: '100px', options: [
        { label: '대기', value: 'pending' },
        { label: '진행중', value: 'in_progress' },
        { label: '완료', value: 'completed' },
      ]},
    ],
    minRows: 1,
    maxRows: 100,
  },
};

// ============================================
// 유통업 프리셋
// ============================================

export const DISTRIBUTION_LOGISTICS_TABLE: SectionPreset = {
  id: 'dist-logistics',
  name: '물류 정보',
  description: '보관 및 배송 조건',
  industry: '유통',
  sectionType: 'table',
  tableConfig: {
    columns: [
      { key: 'warehouse', label: '창고', fieldType: 'reference', width: '130px', isRequired: true, properties: { source: 'warehouses' } },
      { key: 'location', label: '로케이션', fieldType: 'textbox', width: '100px' },
      { key: 'stock_qty', label: '재고수량', fieldType: 'number', width: '90px' },
      { key: 'min_stock', label: '안전재고', fieldType: 'number', width: '90px' },
      { key: 'max_stock', label: '최대재고', fieldType: 'number', width: '90px' },
    ],
    maxRows: 20,
    summaryRow: [
      { columnKey: 'stock_qty', type: 'sum' },
    ],
  },
};

export const DISTRIBUTION_PRODUCT_FIELDS: SectionPreset = {
  id: 'dist-product',
  name: '상품 정보',
  description: '유통 상품 속성',
  industry: '유통',
  sectionType: 'fields',
  fields: [
    { field_key: 'barcode', field_name: '바코드', field_type: 'textbox', is_required: true },
    { field_key: 'shelf_life', field_name: '유통기한(일)', field_type: 'number' },
    { field_key: 'storage_temp', field_name: '보관온도', field_type: 'dropdown', options: [
      { label: '상온', value: 'room' },
      { label: '냉장 (0~10\u00B0C)', value: 'cold' },
      { label: '냉동 (-18\u00B0C 이하)', value: 'frozen' },
    ]},
    { field_key: 'origin_country', field_name: '원산지', field_type: 'textbox' },
  ],
};

// ============================================
// 물류업 프리셋
// ============================================

export const LOGISTICS_VEHICLE_TABLE: SectionPreset = {
  id: 'log-vehicle',
  name: '배차 정보',
  description: '운송 차량 배정 목록',
  industry: '물류',
  sectionType: 'table',
  tableConfig: {
    columns: [
      { key: 'vehicle', label: '차량', fieldType: 'reference', width: '130px', isRequired: true, properties: { source: 'vehicles' } },
      { key: 'driver', label: '기사', fieldType: 'reference', width: '100px', properties: { source: 'employees' } },
      { key: 'load_weight', label: '적재중량(kg)', fieldType: 'number', width: '100px' },
      { key: 'delivery_date', label: '배송일', fieldType: 'date', width: '120px' },
      { key: 'status', label: '상태', fieldType: 'dropdown', width: '90px', options: [
        { label: '배정', value: 'assigned' },
        { label: '운행중', value: 'in_transit' },
        { label: '완료', value: 'delivered' },
      ]},
    ],
    maxRows: 50,
    summaryRow: [
      { columnKey: 'load_weight', type: 'sum' },
    ],
  },
};

// ============================================
// 전체 프리셋 레지스트리
// ============================================

export const SECTION_PRESETS: Record<string, SectionPreset> = {
  // 제조
  'mfg-process': MANUFACTURING_PROCESS_TABLE,
  'mfg-qc': MANUFACTURING_QC_TABLE,
  'mfg-vendor': MANUFACTURING_VENDOR_TABLE,
  // 건설
  'const-spec': CONSTRUCTION_SPEC_FIELDS,
  'const-schedule': CONSTRUCTION_SCHEDULE_TABLE,
  // 유통
  'dist-logistics': DISTRIBUTION_LOGISTICS_TABLE,
  'dist-product': DISTRIBUTION_PRODUCT_FIELDS,
  // 물류
  'log-vehicle': LOGISTICS_VEHICLE_TABLE,
};

/**
 * 산업별 프리셋 필터
 */
export function getPresetsByIndustry(industry: string): SectionPreset[] {
  return Object.values(SECTION_PRESETS).filter(p => p.industry === industry);
}

/**
 * 사용 가능한 산업 목록
 */
export function getAvailableIndustries(): string[] {
  const industries = new Set(Object.values(SECTION_PRESETS).map(p => p.industry));
  return Array.from(industries);
}
