/**
 * 작업실적 조회 타입 정의
 *
 * WorkOrderItem.options.result 기반 작업실적 조회
 */

// 작업실적 데이터 (Frontend)
export interface WorkResult {
  id: string;
  workOrderId: number;        // 작업지시 ID
  lotNo: string;              // 로트번호
  workDate: string;           // 작업 완료일
  workOrderNo: string;        // 작업지시번호
  projectName: string;        // 프로젝트명
  processName: string;        // 공정명
  processCode: string;        // 공정코드
  productName: string;        // 품목명
  specification: string;      // 규격
  quantity: number;           // 지시수량
  productionQty: number;      // 생산수량 (양품+불량)
  goodQty: number;            // 양품수량
  defectQty: number;          // 불량수량
  defectRate: number;         // 불량률 (%)
  inspection: boolean;        // 검사 완료
  packaging: boolean;         // 포장 완료
  workerId: number | null;    // 작업자 ID
  workerName: string | null;  // 작업자 이름
  memo: string | null;        // 메모
}

// 통계 데이터
export interface WorkResultStats {
  totalProduction: number;    // 총 생산수량
  totalGood: number;          // 양품수량
  totalDefect: number;        // 불량수량
  defectRate: number;         // 불량률 (%)
}

// ===== API 타입 정의 =====

// 작업 결과 데이터 (options.result JSON)
export interface WorkResultData {
  completed_at: string;
  good_qty: number;
  defect_qty: number;
  defect_rate: number;
  lot_no: string | null;
  is_inspected: boolean;
  is_packaged: boolean;
  worker_id: number | null;
  memo: string | null;
}

// API 응답 - 작업실적 (WorkOrderItem 기반)
export interface WorkResultApi {
  id: number;
  tenant_id: number;
  work_order_id: number;
  item_id: number | null;
  item_name: string;
  specification: string | null;
  quantity: string;  // decimal
  unit: string | null;
  sort_order: number;
  status: 'waiting' | 'in_progress' | 'completed';
  options: {
    result?: WorkResultData;
  } | null;
  created_at: string;
  updated_at: string;
  worker_name?: string | null;  // 작업자 이름 (백엔드에서 추가)
  // Relations
  work_order?: {
    id: number;
    work_order_no: string;
    project_name: string | null;
    process_id: number | null;
    completed_at: string | null;
    process?: {
      id: number;
      process_name: string;
      process_code: string;
    } | null;
  };
}

// API 페이징 응답
export interface WorkResultApiPaginatedResponse {
  data: WorkResultApi[];
  current_page: number;
  last_page: number;
  per_page: number;
  total: number;
}

// API 통계 응답
export interface WorkResultStatsApi {
  total_production: number;
  total_good: number;
  total_defect: number;
  defect_rate: number;
}

// ===== 변환 함수 =====

// API → Frontend 변환
export function transformApiToFrontend(api: WorkResultApi): WorkResult {
  const result = api.options?.result;
  const goodQty = result?.good_qty ?? 0;
  const defectQty = result?.defect_qty ?? 0;

  return {
    id: String(api.id),
    workOrderId: api.work_order_id,
    lotNo: result?.lot_no || '-',
    workDate: result?.completed_at || api.updated_at,
    workOrderNo: api.work_order?.work_order_no || '-',
    projectName: api.work_order?.project_name || '-',
    processName: api.work_order?.process?.process_name || '-',
    processCode: api.work_order?.process?.process_code || '-',
    productName: api.item_name,
    specification: api.specification || '-',
    quantity: parseFloat(api.quantity) || 0,
    productionQty: goodQty + defectQty,
    goodQty: goodQty,
    defectQty: defectQty,
    defectRate: result?.defect_rate ?? 0,
    inspection: result?.is_inspected ?? false,
    packaging: result?.is_packaged ?? false,
    workerId: result?.worker_id ?? null,
    workerName: api.worker_name ?? null,
    memo: result?.memo ?? null,
  };
}

// Frontend → API 변환 (수정용)
export function transformFrontendToApi(data: Partial<WorkResult>): Record<string, unknown> {
  const result: Record<string, unknown> = {};

  if (data.lotNo !== undefined) result.lot_no = data.lotNo;
  if (data.goodQty !== undefined) result.good_qty = data.goodQty;
  if (data.defectQty !== undefined) result.defect_qty = data.defectQty;
  if (data.inspection !== undefined) result.is_inspected = data.inspection;
  if (data.packaging !== undefined) result.is_packaged = data.packaging;
  if (data.memo !== undefined) result.memo = data.memo;

  return result;
}

// 통계 변환
export function transformStatsApiToFrontend(api: WorkResultStatsApi): WorkResultStats {
  return {
    totalProduction: api.total_production,
    totalGood: api.total_good,
    totalDefect: api.total_defect,
    defectRate: api.defect_rate,
  };
}
