/**
 * POP 공정실행 화면 타입/정규화 유틸 (Phase D)
 *
 * 목적:
 * - 서버 응답의 stringly-typed 필드(수량 string, is_rework "Y"/"true"/"1")를
 *   UI 레이어에서 number/boolean으로 일원화
 * - normalize는 useProcessData 입구 1곳에서만 수행, 이후 컴포넌트는 View만 취급
 */

/** 서버 응답 raw row (일부 string + Phase C number 혼재) */
export interface WorkOrderProcessRaw {
	id: string;
	wo_id: string;
	seq_no: string | number;
	process_code: string;
	process_name: string;
	status: string;
	result_status?: string;
	plan_qty?: string | number | null;
	input_qty?: string | number | null;
	good_qty?: string | number | null;
	defect_qty?: string | number | null;
	concession_qty?: string | number | null;
	total_production_qty?: string | number | null;
	parent_process_id?: string | null;
	is_rework?: string | boolean | null;
	rework_source_id?: string | null;
	started_at?: string | null;
	completed_at?: string | null;
	accepted_by?: string | null;
	accepted_at?: string | null;
	created_date?: string | null;
	batch_id?: string | null;
	equipment_code?: string | null;
	// Phase C 서버 계산 필드
	available_qty?: string | number | null;
	prev_good_qty?: string | number | null;
	my_input_qty?: string | number | null;
	rework_available_qty?: string | number | null;
	split_no?: string | number | null;
	split_total?: string | number | null;
	batch_count?: string | number | null;
	batch_list?: string[] | null;
	batch_index?: number | null;
	/** 신 구조 — 이 wop 에 속한 접수 카드 배열 (wop_result rows) */
	accepted_results?: Array<{
		id: string; // wop_result.id
		seq: string | number;
		status: string;
		result_status?: string;
		input_qty?: string | number | null;
		good_qty?: string | number | null;
		defect_qty?: string | number | null;
		concession_qty?: string | number | null;
		total_production_qty?: string | number | null;
		is_rework?: string | boolean | null;
		rework_source_id?: string | null;
		accepted_by?: string | null;
		accepted_at?: string | null;
		started_at?: string | null;
		completed_at?: string | null;
		equipment_code?: string | null;
		batch_id?: string | null;
	}> | null;
}

/** UI 컴포넌트가 사용하는 정규화 View — 수량 number, 플래그 boolean */
export interface WorkOrderProcessView {
	id: string;
	wo_id: string;
	seq_no: number;
	process_code: string;
	process_name: string;
	status: "acceptable" | "waiting" | "in_progress" | "completed";
	result_status: string;

	// 수량 (모두 number, null 폴백 0)
	plan_qty: number;
	input_qty: number;
	good_qty: number;
	defect_qty: number;
	concession_qty: number;
	total_production_qty: number;

	// 리워크
	is_rework: boolean;
	rework_source_id: string | null;

	// 계층 / 배치
	parent_process_id: string | null;
	batch_id: string | null;

	// 타이밍
	started_at: string | null;
	completed_at: string | null;
	accepted_at: string | null;
	accepted_by: string | null;
	created_date: string | null;

	// 설비
	equipment_code: string | null;

	// Phase C 서버 계산 필드
	available_qty: number;
	prev_good_qty: number | null;
	my_input_qty: number;
	rework_available_qty: number;
	split_no: number | null;
	split_total: number | null;
	batch_count: number;
	batch_list: string[] | null;
	batch_index: number | null;
	/** 신 구조 — 이 wop 에 속한 접수 카드 배열 (정규화됨) */
	accepted_results: Array<{
		id: string; // wop_result.id — 접수/실적 단위 식별자
		seq: number;
		status: "acceptable" | "waiting" | "in_progress" | "completed";
		result_status: string;
		input_qty: number;
		good_qty: number;
		defect_qty: number;
		concession_qty: number;
		total_production_qty: number;
		is_rework: boolean;
		rework_source_id: string | null;
		accepted_by: string | null;
		accepted_at: string | null;
		started_at: string | null;
		completed_at: string | null;
		equipment_code: string | null;
		batch_id: string | null;
	}>;
}

/** 범용 Yes 판정 — "Y"/"true"/"1" (대소문자 유연) 또는 boolean true */
export function isYes(v: unknown): boolean {
	if (v === true) return true;
	if (typeof v !== "string") return false;
	const s = v.trim().toLowerCase();
	return s === "y" || s === "true" || s === "1";
}

/** 리워크 행 여부 — is_rework만 보는 래퍼 (Phase D 집약 대상) */
export function isReworkProcess(
	row: { is_rework?: string | boolean | null } | null | undefined,
): boolean {
	if (!row) return false;
	return isYes(row.is_rework);
}

/** 수량 정규화 — string/null → number, NaN 방지 */
function toInt(v: unknown): number {
	if (typeof v === "number" && Number.isFinite(v)) return v;
	if (v == null) return 0;
	const n = parseInt(String(v), 10);
	return Number.isFinite(n) ? n : 0;
}

/** nullable 숫자 정규화 — null 유지 */
function toNullableInt(v: unknown): number | null {
	if (v == null) return null;
	if (typeof v === "number") return Number.isFinite(v) ? v : null;
	const n = parseInt(String(v), 10);
	return Number.isFinite(n) ? n : null;
}

/**
 * 서버 raw row → 정규화 View
 * - 수량 문자열 → number (NaN 방지)
 * - is_rework → boolean
 * - seq_no → number
 * - Phase C 계산 필드 number 통일
 */
export function normalizeWorkOrderProcess(
	raw: WorkOrderProcessRaw,
): WorkOrderProcessView {
	return {
		id: String(raw.id || ""),
		wo_id: String(raw.wo_id || ""),
		seq_no: toInt(raw.seq_no),
		process_code: String(raw.process_code || ""),
		process_name: String(raw.process_name || ""),
		status: (raw.status as WorkOrderProcessView["status"]) || "waiting",
		result_status: String(raw.result_status || ""),
		plan_qty: toInt(raw.plan_qty),
		input_qty: toInt(raw.input_qty),
		good_qty: toInt(raw.good_qty),
		defect_qty: toInt(raw.defect_qty),
		concession_qty: toInt(raw.concession_qty),
		total_production_qty: toInt(raw.total_production_qty),
		is_rework: isYes(raw.is_rework),
		rework_source_id: raw.rework_source_id ?? null,
		parent_process_id: raw.parent_process_id ?? null,
		batch_id: raw.batch_id ?? null,
		started_at: raw.started_at ?? null,
		completed_at: raw.completed_at ?? null,
		accepted_at: raw.accepted_at ?? null,
		accepted_by: raw.accepted_by ?? null,
		created_date: raw.created_date ?? null,
		equipment_code: raw.equipment_code ?? null,
		// Phase C
		available_qty: toInt(raw.available_qty),
		prev_good_qty: toNullableInt(raw.prev_good_qty),
		my_input_qty: toInt(raw.my_input_qty),
		rework_available_qty: toInt(raw.rework_available_qty),
		split_no: toNullableInt(raw.split_no),
		split_total: toNullableInt(raw.split_total),
		batch_count: toInt(raw.batch_count),
		batch_list: Array.isArray(raw.batch_list) ? raw.batch_list : null,
		batch_index: raw.batch_index ?? null,
		accepted_results: Array.isArray(raw.accepted_results)
			? raw.accepted_results.map((ar) => ({
					id: String(ar.id || ""),
					seq: toInt(ar.seq),
					status:
						(ar.status as WorkOrderProcessView["status"]) || "in_progress",
					result_status: String(ar.result_status || ""),
					input_qty: toInt(ar.input_qty),
					good_qty: toInt(ar.good_qty),
					defect_qty: toInt(ar.defect_qty),
					concession_qty: toInt(ar.concession_qty),
					total_production_qty: toInt(ar.total_production_qty),
					is_rework: isYes(ar.is_rework),
					rework_source_id: ar.rework_source_id ?? null,
					accepted_by: ar.accepted_by ?? null,
					accepted_at: ar.accepted_at ?? null,
					started_at: ar.started_at ?? null,
					completed_at: ar.completed_at ?? null,
					equipment_code: ar.equipment_code ?? null,
					batch_id: ar.batch_id ?? null,
				}))
			: [],
	};
}
