/**
 * Template Service
 * 섹션 템플릿 및 템플릿 필드 관련 도메인 로직 중앙화
 * - validation (fieldService 재사용)
 * - parsing (fieldService 재사용)
 * - transform (폼 ↔ API)
 * - defaults
 */

import type { SectionTemplate, TemplateField, ItemSection } from '@/contexts/ItemMasterContext';
import { fieldService } from './fieldService';

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

export type TemplateType = 'fields' | 'bom';

export interface SectionTemplateFormData {
  title: string;
  description: string;
  category: string[];
  templateType: TemplateType;
}

export interface TemplateFieldFormData {
  name: string;
  key: string;
  inputType: 'textbox' | 'dropdown' | 'checkbox' | 'number' | 'date' | 'textarea';
  required: boolean;
  options: string;
  description: string;
  multiColumn: boolean;
  columnCount: number;
  columnNames: string[];
  inputMode: 'custom' | 'master';
  selectedMasterFieldId: string;
}

export interface TemplateValidationResult {
  valid: boolean;
  errors: {
    title?: string;
    template_type?: string;
  };
}

export interface TemplateFieldValidationResult {
  valid: boolean;
  errors: {
    field_name?: string;
    field_key?: string;
    field_type?: string;
  };
}

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

export const templateService = {
  // ===== Section Template Validation =====

  /**
   * 섹션 템플릿 폼 유효성 검사
   */
  validate: (data: Partial<SectionTemplateFormData>): TemplateValidationResult => {
    const errors: TemplateValidationResult['errors'] = {};

    if (!data.title || !data.title.trim()) {
      errors.title = '섹션 제목을 입력해주세요';
    }

    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 };
  },

  // ===== Template Field Validation (fieldService 재사용) =====

  /**
   * 템플릿 필드 폼 유효성 검사
   */
  validateField: (data: Partial<TemplateFieldFormData>): TemplateFieldValidationResult => {
    const errors: TemplateFieldValidationResult['errors'] = {};

    const nameValidation = fieldService.validateFieldName(data.name || '');
    if (!nameValidation.valid) {
      errors.field_name = (nameValidation as { valid: false; error: string }).error;
    }

    const keyValidation = fieldService.validateFieldKey(data.key || '');
    if (!keyValidation.valid) {
      errors.field_key = (keyValidation as { valid: false; error: string }).error;
    }

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

  /**
   * 필드명 유효성 검사 (fieldService 위임)
   */
  validateFieldName: fieldService.validateFieldName,

  /**
   * 필드 키 유효성 검사 (fieldService 위임)
   */
  validateFieldKey: fieldService.validateFieldKey,

  /**
   * 필드 키 패턴 정규식 (fieldService 재사용)
   */
  fieldKeyPattern: fieldService.fieldKeyPattern,

  // ===== Parsing (fieldService 재사용) =====

  /**
   * field_key에서 사용자 입력 부분 추출 (fieldService 위임)
   */
  extractUserInputFromFieldKey: fieldService.extractUserInputFromFieldKey,

  /**
   * 옵션 문자열을 배열로 파싱 (fieldService 위임)
   */
  parseOptionsFromString: fieldService.parseOptionsFromString,

  /**
   * 옵션 배열을 문자열로 변환 (fieldService 위임)
   */
  optionsToString: fieldService.optionsToString,

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

  /**
   * 섹션 템플릿 폼 데이터 → API 섹션 타입 변환
   */
  toApiSectionType: (templateType: TemplateType): 'BASIC' | 'BOM' | 'CUSTOM' => {
    return templateType === 'bom' ? 'BOM' : 'BASIC';
  },

  /**
   * API 섹션 타입 → UI 템플릿 타입 변환
   */
  toUiTemplateType: (sectionType: 'BASIC' | 'BOM' | 'CUSTOM'): TemplateType => {
    return sectionType === 'BOM' ? 'bom' : 'fields';
  },

  /**
   * SectionTemplate → 폼 데이터 변환
   */
  toFormData: (template: SectionTemplate): SectionTemplateFormData => {
    return {
      title: template.template_name,
      description: template.description || '',
      category: template.category || [],
      templateType: templateService.toUiTemplateType(template.section_type),
    };
  },

  /**
   * 폼 데이터 → 독립 섹션 생성 요청 객체 변환
   */
  toIndependentSectionRequest: (formData: SectionTemplateFormData) => {
    return {
      title: formData.title,
      type: formData.templateType as 'fields' | 'bom',
      description: formData.description || undefined,
      is_template: true,
      is_default: false,
    };
  },

  /**
   * 폼 데이터 → 섹션 업데이트 요청 객체 변환
   */
  toUpdateRequest: (formData: SectionTemplateFormData): Partial<ItemSection> => {
    return {
      title: formData.title,
      description: formData.description || undefined,
      section_type: templateService.toApiSectionType(formData.templateType),
    };
  },

  /**
   * TemplateField → 폼 데이터 변환
   */
  fieldToFormData: (field: TemplateField): TemplateFieldFormData => {
    return {
      name: field.name,
      key: templateService.extractUserInputFromFieldKey(field.fieldKey),
      inputType: field.property.inputType,
      required: field.property.required,
      options: field.property.options?.join(', ') || '',
      description: field.description || '',
      multiColumn: field.property.multiColumn || false,
      columnCount: field.property.columnCount || 2,
      columnNames: field.property.columnNames || ['컬럼1', '컬럼2'],
      inputMode: 'custom',
      selectedMasterFieldId: '',
    };
  },

  /**
   * 폼 데이터 → 필드 업데이트 요청 객체 변환
   */
  fieldToUpdateRequest: (formData: TemplateFieldFormData) => {
    const supportsMultiColumn = formData.inputType === 'textbox' || formData.inputType === 'textarea';

    return {
      field_name: formData.name,
      field_key: formData.key,
      field_type: formData.inputType,
      is_required: formData.required,
      placeholder: formData.description || null,
      options: formData.inputType === 'dropdown' && formData.options.trim()
        ? formData.options.split(',').map(o => ({ label: o.trim(), value: o.trim() }))
        : null,
      properties: {
        inputType: formData.inputType,
        required: formData.required,
        multiColumn: supportsMultiColumn ? formData.multiColumn : undefined,
        columnCount: supportsMultiColumn && formData.multiColumn ? formData.columnCount : undefined,
        columnNames: supportsMultiColumn && formData.multiColumn ? formData.columnNames : undefined,
      },
    };
  },

  // ===== Defaults =====

  /**
   * 새 섹션 템플릿 생성 시 기본값
   */
  getDefaultFormData: (): SectionTemplateFormData => ({
    title: '',
    description: '',
    category: [],
    templateType: 'fields',
  }),

  /**
   * 새 템플릿 필드 생성 시 기본값
   */
  getDefaultFieldFormData: (): TemplateFieldFormData => ({
    name: '',
    key: '',
    inputType: 'textbox',
    required: false,
    options: '',
    description: '',
    multiColumn: false,
    columnCount: 2,
    columnNames: ['컬럼1', '컬럼2'],
    inputMode: 'custom',
    selectedMasterFieldId: '',
  }),

  /**
   * 지원하는 필드 타입 목록 (fieldService 재사용)
   */
  fieldTypes: fieldService.fieldTypes,

  /**
   * 섹션 타입 옵션 목록
   */
  sectionTypes: [
    { value: 'fields', label: '일반 섹션' },
    { value: 'bom', label: '모듈 섹션 (BOM)' },
  ] as const,
};
