/**
 * 생산/물류 현황 (Production/Logistics) 변환
 */

import type {
  DailyProductionApiResponse,
  UnshippedApiResponse,
  ConstructionApiResponse,
} from '../types';
import type {
  DailyProductionData,
  UnshippedData,
  ConstructionData,
} from '@/components/business/CEODashboard/types';

const WORK_STATUS_MAP: Record<string, '진행중' | '대기' | '완료'> = {
  in_progress: '진행중',
  pending: '대기',
  completed: '완료',
};

const CONSTRUCTION_STATUS_MAP: Record<string, '진행중' | '예정' | '완료'> = {
  in_progress: '진행중',
  scheduled: '예정',
  completed: '완료',
};

/**
 * DailyProduction API 응답 → Frontend DailyProductionData 변환
 */
export function transformDailyProductionResponse(api: DailyProductionApiResponse): DailyProductionData {
  const dateObj = new Date(api.date);
  const dayNames = ['일요일', '월요일', '화요일', '수요일', '목요일', '금요일', '토요일'];
  const formattedDate = `${dateObj.getFullYear()}년 ${dateObj.getMonth() + 1}월 ${dateObj.getDate()}일 ${api.day_of_week || dayNames[dateObj.getDay()]}`;

  return {
    date: formattedDate,
    processes: api.processes.map((proc) => ({
      processName: proc.process_name,
      totalWork: proc.total_work,
      todo: proc.todo,
      inProgress: proc.in_progress,
      completed: proc.completed,
      urgent: proc.urgent,
      subLine: proc.sub_line,
      regular: proc.regular,
      workerCount: proc.worker_count,
      workItems: proc.work_items.map((item) => ({
        id: item.id,
        orderNo: item.order_no,
        client: item.client,
        product: item.product,
        quantity: item.quantity,
        status: WORK_STATUS_MAP[item.status] ?? '대기',
      })),
      workers: proc.workers.map((w) => ({
        name: w.name,
        assigned: w.assigned,
        completed: w.completed,
        rate: w.rate,
      })),
    })),
    shipment: {
      expectedAmount: api.shipment.expected_amount,
      expectedCount: api.shipment.expected_count,
      actualAmount: api.shipment.actual_amount,
      actualCount: api.shipment.actual_count,
    },
  };
}

/**
 * Unshipped API 응답 → Frontend UnshippedData 변환
 */
export function transformUnshippedResponse(api: UnshippedApiResponse): UnshippedData {
  return {
    items: api.items.map((item) => ({
      id: item.id,
      portNo: item.port_no,
      siteName: item.site_name,
      orderClient: item.order_client,
      dueDate: item.due_date,
      daysLeft: item.days_left,
    })),
  };
}

/**
 * Construction API 응답 → Frontend ConstructionData 변환
 */
export function transformConstructionResponse(api: ConstructionApiResponse): ConstructionData {
  return {
    thisMonth: api.this_month,
    completed: api.completed,
    items: api.items.map((item) => ({
      id: item.id,
      siteName: item.site_name,
      client: item.client,
      startDate: item.start_date,
      endDate: item.end_date,
      progress: item.progress,
      status: CONSTRUCTION_STATUS_MAP[item.status] ?? '진행중',
    })),
  };
}
