/**
 * 배차차량관리 서버 액션
 */

'use server';

import type {
  VehicleDispatchItem,
  VehicleDispatchDetail,
  VehicleDispatchStats,
  VehicleDispatchEditFormData,
} from './types';
import { buildApiUrl } from '@/lib/api/query-params';
import { executeServerAction } from '@/lib/api/execute-server-action';
import { executePaginatedAction } from '@/lib/api/execute-paginated-action';

// ===== 페이지네이션 타입 =====
interface PaginationMeta {
  currentPage: number;
  lastPage: number;
  perPage: number;
  total: number;
}

// ===== API 응답 → 프론트 타입 변환 =====
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function transformToListItem(data: any): VehicleDispatchItem {
  const options = data.options || {};
  const shipment = data.shipment || {};
  const order = shipment.order || {};
  const orderInfo = shipment.order_info || {};
  return {
    id: String(data.id),
    dispatchNo: options.dispatch_no || `DC-${data.id}`,
    shipmentNo: shipment.shipment_no || '',
    lotNo: shipment.lot_no || '',
    siteName: orderInfo.site_name || order.site_name || shipment.site_name || '',
    orderCustomer: orderInfo.customer_name || order.client_name || shipment.customer_name || '',
    logisticsCompany: data.logistics_company || '',
    tonnage: data.tonnage || '',
    supplyAmount: options.supply_amount || 0,
    vat: options.vat || 0,
    totalAmount: options.total_amount || 0,
    freightCostType: options.freight_cost_type || 'prepaid',
    vehicleNo: data.vehicle_no || '',
    driverContact: data.driver_contact || '',
    writer: shipment.creator?.name || order.writer?.name || options.writer || '',
    arrivalDateTime: data.arrival_datetime || '',
    status: options.freight_cost_type ? 'completed' : 'draft',
    remarks: data.remarks || '',
  };
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
function transformToDetail(data: any): VehicleDispatchDetail {
  const options = data.options || {};
  const shipment = data.shipment || {};
  const order = shipment.order || {};
  const orderInfo = shipment.order_info || {};
  return {
    id: String(data.id),
    dispatchNo: options.dispatch_no || `DC-${data.id}`,
    shipmentNo: shipment.shipment_no || '',
    lotNo: shipment.lot_no || '',
    siteName: orderInfo.site_name || order.site_name || shipment.site_name || '',
    orderCustomer: orderInfo.customer_name || order.client_name || shipment.customer_name || '',
    freightCostType: options.freight_cost_type || 'prepaid',
    status: options.freight_cost_type ? 'completed' : 'draft',
    writer: shipment.creator?.name || order.writer?.name || options.writer || '',
    logisticsCompany: data.logistics_company || '',
    arrivalDateTime: data.arrival_datetime || '',
    tonnage: data.tonnage || '',
    vehicleNo: data.vehicle_no || '',
    driverContact: data.driver_contact || '',
    remarks: data.remarks || '',
    supplyAmount: options.supply_amount || 0,
    vat: options.vat || 0,
    totalAmount: options.total_amount || 0,
  };
}

// ===== 배차차량 목록 조회 =====
export async function getVehicleDispatches(params?: {
  page?: number;
  perPage?: number;
  search?: string;
  status?: string;
  startDate?: string;
  endDate?: string;
}): Promise<{
  success: boolean;
  data: VehicleDispatchItem[];
  pagination: PaginationMeta;
  error?: string;
}> {
  return executePaginatedAction({
    url: buildApiUrl('/api/v1/vehicle-dispatches', {
      search: params?.search,
      status: params?.status !== 'all' ? params?.status : undefined,
      start_date: params?.startDate,
      end_date: params?.endDate,
      page: params?.page,
      per_page: params?.perPage,
    }),
    transform: transformToListItem,
    errorMessage: '배차차량 목록 조회에 실패했습니다.',
  });
}

// ===== 배차차량 통계 조회 =====
export async function getVehicleDispatchStats(): Promise<{
  success: boolean;
  data?: VehicleDispatchStats;
  error?: string;
}> {
  return executeServerAction<
    { prepaid_amount: number; collect_amount: number; total_amount: number },
    VehicleDispatchStats
  >({
    url: buildApiUrl('/api/v1/vehicle-dispatches/stats'),
    transform: (data) => ({
      prepaidAmount: data.prepaid_amount,
      collectAmount: data.collect_amount,
      totalAmount: data.total_amount,
    }),
    errorMessage: '배차차량 통계 조회에 실패했습니다.',
  });
}

// ===== 배차차량 상세 조회 =====
export async function getVehicleDispatchById(id: string): Promise<{
  success: boolean;
  data?: VehicleDispatchDetail;
  error?: string;
}> {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/vehicle-dispatches/${id}`),
    transform: transformToDetail,
    errorMessage: '배차차량 상세 조회에 실패했습니다.',
  });
}

// ===== 배차차량 수정 =====
export async function updateVehicleDispatch(
  id: string,
  data: VehicleDispatchEditFormData
): Promise<{ success: boolean; error?: string }> {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/vehicle-dispatches/${id}`),
    method: 'PUT',
    body: {
      freight_cost_type: data.freightCostType,
      logistics_company: data.logisticsCompany,
      arrival_datetime: data.arrivalDateTime,
      tonnage: data.tonnage,
      vehicle_no: data.vehicleNo,
      driver_contact: data.driverContact,
      remarks: data.remarks,
      supply_amount: data.supplyAmount,
      vat: data.vat,
      total_amount: data.totalAmount,
      status: undefined, // 상태는 별도로 관리
    },
    errorMessage: '배차차량 수정에 실패했습니다.',
  });
}
