/**
 * Section Service
 * 섹션 관련 도메인 로직 중앙화
 * - validation
 * - parsing
 * - transform (폼 ↔ API)
 * - defaults
 */

import type { ItemSection, ItemPage } from '@/contexts/ItemMasterContext';

// ===== Types =====

export type SectionType = 'BASIC' | 'BOM' | 'CUSTOM';
export type SectionInputType = 'fields' | 'bom';

export interface SectionFormData {
  title: string;
  description: string;
  sectionType: SectionInputType;
  inputMode: 'custom' | 'template';
  templateId: number | null;
}

export interface SectionValidationResult {
  valid: boolean;
  errors: {
    title?: string;
    section_type?: string;
  };
}

// ===== Service =====

export const sectionService = {
  // ===== Validation =====

  /**
   * 전체 섹션 폼 유효성 검사
   */
  validate: (data: Partial<SectionFormData>): SectionValidationResult => {
    const errors: SectionValidationResult['errors'] = {};

    const titleValidation = sectionService.validateTitle(data.title || '');
    if (!titleValidation.valid) {
      errors.title = titleValidation.error;
    }

    return {
      valid: Object.keys(errors).length === 0,
      errors,
    };
  },

  /**
   * 섹션 제목 유효성 검사
   */
  validateTitle: (title: string): { valid: boolean; error?: string } => {
    if (!title || !title.trim()) {
      return { valid: false, error: '섹션 제목을 입력해주세요' };
    }
    return { valid: true };
  },

  /**
   * 섹션 타입 유효성 검사
   */
  validateSectionType: (type: string): { valid: boolean; error?: string } => {
    const validTypes = ['BASIC', 'BOM', 'CUSTOM'];
    if (!validTypes.includes(type)) {
      return { valid: false, error: '유효하지 않은 섹션 타입입니다' };
    }
    return { valid: true };
  },

  // ===== Transform =====

  /**
   * UI 섹션 타입을 API 섹션 타입으로 변환
   */
  toApiSectionType: (inputType: SectionInputType): SectionType => {
    return inputType === 'bom' ? 'BOM' : 'BASIC';
  },

  /**
   * API 섹션 타입을 UI 섹션 타입으로 변환
   */
  toUiSectionType: (sectionType: SectionType): SectionInputType => {
    return sectionType === 'BOM' ? 'bom' : 'fields';
  },

  /**
   * 폼 데이터 → API 요청 객체 변환
   */
  toApiRequest: (
    formData: SectionFormData,
    pageId: number,
    orderNo: number
  ): Omit<ItemSection, 'id' | 'created_at' | 'updated_at'> => {
    const sectionType = sectionService.toApiSectionType(formData.sectionType);

    return {
      page_id: pageId,
      title: formData.title,
      section_type: sectionType,
      description: formData.description || undefined,
      order_no: orderNo,
      is_template: false,
      is_default: false,
      is_collapsible: true,
      is_default_open: true,
      fields: [],
      bom_items: sectionType === 'BOM' ? [] : undefined,
    };
  },

  /**
   * ItemSection → 폼 데이터 변환
   */
  toFormData: (section: ItemSection): SectionFormData => {
    return {
      title: section.title,
      description: section.description || '',
      sectionType: sectionService.toUiSectionType(section.section_type),
      inputMode: 'custom',
      templateId: null,
    };
  },

  // ===== Utilities =====

  /**
   * 새 섹션 생성 시 기본값
   */
  getDefaultFormData: (): SectionFormData => ({
    title: '',
    description: '',
    sectionType: 'fields',
    inputMode: 'custom',
    templateId: null,
  }),

  /**
   * 섹션이 이미 페이지에 연결되어 있는지 확인
   */
  isLinkedToPage: (sectionId: number, page: ItemPage): boolean => {
    return page.sections.some(s => s.id === sectionId);
  },

  /**
   * 섹션 타입 옵션 목록
   */
  sectionTypes: [
    { value: 'fields', label: '일반 섹션', description: '필드 항목 관리' },
    { value: 'bom', label: '모듈 섹션 (BOM)', description: '자재명세서 관리' },
  ] as const,
};
