/**
 * 절곡품 관리 타입 정의
 *
 * API: bending-items (기초관리) + guiderail-models (모델관리)
 */

// --- 공용 ---

/** 절곡 입력 데이터 (bendingData JSON 배열 원소) */
export interface BendingData {
  no: number;
  input: number;
  rate: string;     // '' | '-1' | '1'
  sum: number;      // 누적합 (자동 계산)
  color: boolean;   // 음영
  aAngle: boolean;  // A각
}

/** 모델 카테고리 */
export type ModelCategory =
  | 'GUIDERAIL_MODEL'
  | 'SHUTTERBOX_MODEL'
  | 'BOTTOMBAR_MODEL';

// --- 기초관리 (bending-items) ---

/** 기초관리 목록 아이템 (GET /api/v1/bending-items) */
export interface BendingItem {
  id: number;
  code: string;
  name: string;
  item_type: string;
  item_category: string;
  item_name: string;
  item_sep: string;          // 대분류: '스크린' | '철재'
  item_bending: string;      // 분류: '가이드레일' | '케이스' | '하단마감재' 등
  item_spec: string;         // 규격
  material: string;          // 재질
  model_name: string | null;
  model_UA: string;          // '인정' | '비인정'
  search_keyword: string | null;
  rail_width: number | null;
  registration_date: string | null;
  author: string | null;
  memo: string | null;
  exit_direction: string | null;   // 점검구 방향 (케이스 전용)
  front_bottom_width: number | null;
  box_width: number | null;
  box_height: number | null;
  bendingData: BendingData[];
  prefix: string;
  length_code: string;
  length_mm: number;
  legacy_bending_num: number | null;
  image_url: string | null;
  width_sum: number;
  bend_count: number;
  created_at: string;
  updated_at?: string;
  modified_by?: string | null;
}

/** 기초관리 필터 옵션 (GET /api/v1/bending-items/filters) */
export interface BendingItemFilters {
  item_sep: string[];
  item_bending: string[];
  material: string[];
  model_UA: string[];
  model_name: string[];
}

/** 기초관리 등록/수정 폼 데이터 */
export interface BendingItemFormData {
  code: string;
  name: string;
  item_name: string;
  item_sep: string;
  item_bending: string;
  material: string;
  item_spec: string;
  model_name: string;
  model_UA: string;
  registration_date: string;
  search_keyword: string;
  memo: string;
  // 케이스 전용
  exit_direction: string;
  front_bottom_width: string;
  rail_width: string;
  box_width: string;
  box_height: string;
  // 절곡 데이터
  bendingData: BendingData[];
}

// --- 모델관리 (guiderail-models) ---

/** 부품 조립 데이터 */
export interface ComponentData {
  orderNumber: number;
  itemName: string;
  material: string;
  quantity: number;
  width_sum: number;
  bendingData: BendingData[];
  imageUrl?: string;
  sourceItemId?: number;
  legacy_bending_num?: string;
}

/** 모델 목록 아이템 (GET /api/v1/guiderail-models) */
export interface GuiderailModel {
  id: number;
  code: string;
  name: string;
  item_category: ModelCategory;
  model_name: string;
  check_type: string;          // 형상: '벽면형' | '측면형' (가이드레일) / 점검구 방향 (케이스)
  rail_width: number | null;
  rail_length: number | null;
  finishing_type: string;      // 마감: 'SUS마감' | 'EGI마감'
  item_sep: string;            // 대분류
  model_UA: string;            // 인정/비인정
  component_count: number;
  material_summary: Record<string, number>;  // { "SUS 1.2T": 599, "EGI 1.55T": 894 }
  // 케이스 전용
  exit_direction?: string | null;    // 점검구 방향 (케이스: '양면 점검구' | '밑면 점검구' | '후면 점검구')
  front_bottom_width?: number | null;
  box_width?: number | null;
  box_height?: number | null;
  bar_width?: number | null;       // 하단마감재 가로
  bar_height?: number | null;      // 하단마감재 세로
  search_keyword?: string | null;
  author?: string | null;
  memo?: string | null;
  registration_date?: string | null;
  image_url?: string | null;
  created_at: string;
  updated_at?: string;
  modified_by?: string | null;
}

/** 모델 상세 (GET /api/v1/guiderail-models/{id}) */
export interface GuiderailModelDetail extends GuiderailModel {
  components: ComponentData[];
}

/** 모델 필터 옵션 (GET /api/v1/guiderail-models/filters) */
export interface GuiderailModelFilters {
  item_sep: string[];
  model_UA: string[];
  check_type: string[];
  model_name: string[];
  finishing_type: string[];
}

/** 모델 등록/수정 폼 데이터 */
export interface GuiderailModelFormData {
  item_category: ModelCategory;
  model_name: string;
  check_type: string;
  rail_width: string;
  rail_length: string;
  finishing_type: string;
  item_sep: string;
  model_UA: string;
  registration_date: string;
  author: string;
  search_keyword: string;
  memo: string;
  // 케이스 전용
  front_bottom_width: string;
  // 부품 조립
  components: ComponentData[];
}

// --- 유틸리티 ---

/** bendingData에서 연신율 후 값 계산 */
export function calculateRateResult(input: number, rate: string): number {
  const rateNum = Number(rate);
  if (!rate || rate === '-' || isNaN(rateNum)) return input;
  return input + rateNum;
}

/** bendingData 배열에서 합계 재계산 */
export function recalculateSums(data: BendingData[]): BendingData[] {
  let cumulative = 0;
  return data.map((d, i) => {
    const rateResult = calculateRateResult(d.input, d.rate);
    cumulative += rateResult;
    return { ...d, no: i + 1, sum: cumulative };
  });
}

/** 폭합계 (마지막 행의 sum) */
export function getWidthSum(data: BendingData[]): number {
  if (data.length === 0) return 0;
  return data[data.length - 1].sum;
}

/** 절곡횟수 (rate가 빈 문자열이 아닌 행의 수) */
export function getBendCount(data: BendingData[]): number {
  return data.filter(d => d.rate !== '').length;
}

/** 빈 BendingData 생성 */
export function createEmptyBendingData(no: number): BendingData {
  return { no, input: 0, rate: '', sum: 0, color: false, aAngle: false };
}

/** API 부품 응답을 ComponentData로 변환 */
export function parseApiComponent(raw: Record<string, unknown>, index: number): ComponentData {
  const inputList = (raw.inputList as string[]) || [];
  const rateList = (raw.bendingrateList as string[]) || [];
  const colorList = (raw.colorList as boolean[]) || [];
  const aList = (raw.AList as boolean[]) || [];
  const sumList = (raw.sumList as string[]) || [];

  const bendingData: BendingData[] = inputList.map((input, i) => ({
    no: i + 1,
    input: Number(input) || 0,
    rate: rateList[i] ?? '',
    sum: Number(sumList[i]) || 0,
    color: colorList[i] ?? false,
    aAngle: aList[i] ?? false,
  }));

  const lastSum = sumList.length > 0 ? Number(sumList[sumList.length - 1]) || 0 : 0;

  return {
    orderNumber: (raw.orderNumber as number) || index + 1,
    itemName: (raw.itemName as string) || '',
    material: (raw.material as string) || '',
    quantity: (raw.quantity as number) || 1,
    width_sum: lastSum,
    bendingData,
    imageUrl: (raw.image_url as string) || undefined,
    sourceItemId: (raw.sam_item_id as number) || undefined,
    legacy_bending_num: (raw.num as string) || undefined,
  };
}

/** 이미지 URL 생성 */
export function getBendingImageUrl(fileId: number | string): string {
  const apiUrl = process.env.NEXT_PUBLIC_API_URL || '';
  return `${apiUrl}/api/v1/files/${fileId}/view`;
}

/** 재질별 폭합 계산 */
export function calculateMaterialSummary(
  components: ComponentData[]
): Record<string, number> {
  const summary: Record<string, number> = {};
  for (const comp of components) {
    if (comp.material) {
      summary[comp.material] = (summary[comp.material] || 0) + comp.width_sum * comp.quantity;
    }
  }
  return summary;
}
