'use server';

import { executePaginatedAction } from '@/lib/api/execute-paginated-action';
import { executeServerAction } from '@/lib/api/execute-server-action';
import { buildApiUrl } from '@/lib/api/query-params';
import type {
  ApiProductionOrder,
  ApiProductionOrderDetail,
  ProductionOrder,
  ProductionOrderDetail,
  ProductionOrderStats,
  ProductionOrderListParams,
} from './types';

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

function formatDateOnly(dateStr: string | null | undefined): string {
  if (!dateStr) return '-';
  // ISO "2026-02-21T18:12:31.000000Z" 또는 "2026-02-22 03:12:31" 형식 모두 지원
  return dateStr.split(/[T ]/)[0];
}

function transformApiToFrontend(data: ApiProductionOrder): ProductionOrder {
  return {
    id: String(data.id),
    orderNumber: data.order_no,
    siteName: data.site_name || '',
    clientName: data.client_name || data.client?.name || '',
    quantity: parseFloat(String(data.quantity)) || 0,
    nodeCount: data.node_count || data.nodes_count || 0,
    deliveryDate: data.delivery_date || '',
    productionOrderedAt: formatDateOnly(data.production_ordered_at),
    productionStatus: data.production_status,
    workOrderCount: data.work_orders_count,
    workOrderProgress: {
      total: data.work_order_progress?.total || 0,
      completed: data.work_order_progress?.completed || 0,
      inProgress: data.work_order_progress?.in_progress || 0,
    },
  };
}

function transformDetailApiToFrontend(data: ApiProductionOrderDetail): ProductionOrderDetail {
  const order = transformApiToFrontend(data.order);
  return {
    ...order,
    productionOrderedAt: formatDateOnly(data.production_ordered_at) || order.productionOrderedAt,
    productionStatus: data.production_status || order.productionStatus,
    nodeCount: data.node_count || order.nodeCount,
    workOrderProgress: {
      total: data.work_order_progress?.total || 0,
      completed: data.work_order_progress?.completed || 0,
      inProgress: data.work_order_progress?.in_progress || 0,
    },
    workOrders: (data.work_orders || []).map((wo) => ({
      id: wo.id,
      workOrderNo: wo.work_order_no,
      processName: wo.process_name,
      quantity: wo.quantity,
      status: wo.status,
      assignees: wo.assignees || [],
    })),
    bomProcessGroups: (data.bom_process_groups || []).map((group) => ({
      processName: group.process_name,
      sizeSpec: group.size_spec,
      items: (group.items || []).map((item) => ({
        id: item.id,
        itemCode: item.item_code,
        itemName: item.item_name,
        spec: item.spec || '',
        unit: item.unit || '',
        quantity: item.quantity ?? 0,
        unitPrice: item.unit_price ?? 0,
        totalPrice: item.total_price ?? 0,
        nodeName: item.node_name || '',
      })),
    })),
  };
}

// ===== Server Actions =====

// 목록 조회
export async function getProductionOrders(params: ProductionOrderListParams) {
  return executePaginatedAction<ApiProductionOrder, ProductionOrder>({
    url: buildApiUrl('/api/v1/production-orders', {
      search: params.search,
      production_status: params.productionStatus,
      sort_by: params.sortBy,
      sort_dir: params.sortDir,
      page: params.page,
      per_page: params.perPage,
    }),
    transform: transformApiToFrontend,
    errorMessage: '생산지시 목록 조회에 실패했습니다.',
  });
}

// 상태별 통계
export async function getProductionOrderStats() {
  return executeServerAction<ProductionOrderStats>({
    url: buildApiUrl('/api/v1/production-orders/stats'),
    errorMessage: '생산지시 통계 조회에 실패했습니다.',
  });
}

// 상세 조회
export async function getProductionOrderDetail(orderId: string) {
  return executeServerAction<ApiProductionOrderDetail, ProductionOrderDetail>({
    url: buildApiUrl(`/api/v1/production-orders/${orderId}`),
    transform: transformDetailApiToFrontend,
    errorMessage: '생산지시 상세 조회에 실패했습니다.',
  });
}
