/**
 * 배차차량관리 서버 액션
 *
 * 현재: Mock 데이터 반환
 * 추후: API 연동 시 serverFetch 사용
 */

'use server';

import type {
  VehicleDispatchItem,
  VehicleDispatchDetail,
  VehicleDispatchStats,
  VehicleDispatchEditFormData,
} from './types';
import {
  mockVehicleDispatchItems,
  mockVehicleDispatchDetail,
  mockVehicleDispatchStats,
} from './mockData';

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

// ===== 배차차량 목록 조회 =====
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;
}> {
  try {
    let items = [...mockVehicleDispatchItems];

    // 상태 필터
    if (params?.status && params.status !== 'all') {
      items = items.filter((item) => item.status === params.status);
    }

    // 검색 필터
    if (params?.search) {
      const s = params.search.toLowerCase();
      items = items.filter(
        (item) =>
          item.dispatchNo.toLowerCase().includes(s) ||
          item.shipmentNo.toLowerCase().includes(s) ||
          item.siteName.toLowerCase().includes(s) ||
          item.orderCustomer.toLowerCase().includes(s) ||
          item.vehicleNo.toLowerCase().includes(s)
      );
    }

    // 페이지네이션
    const page = params?.page || 1;
    const perPage = params?.perPage || 20;
    const total = items.length;
    const lastPage = Math.ceil(total / perPage);
    const startIndex = (page - 1) * perPage;
    const paginatedItems = items.slice(startIndex, startIndex + perPage);

    return {
      success: true,
      data: paginatedItems,
      pagination: {
        currentPage: page,
        lastPage,
        perPage,
        total,
      },
    };
  } catch (error) {
    console.error('[VehicleDispatchActions] getVehicleDispatches error:', error);
    return {
      success: false,
      data: [],
      pagination: { currentPage: 1, lastPage: 1, perPage: 20, total: 0 },
      error: '서버 오류가 발생했습니다.',
    };
  }
}

// ===== 배차차량 통계 조회 =====
export async function getVehicleDispatchStats(): Promise<{
  success: boolean;
  data?: VehicleDispatchStats;
  error?: string;
}> {
  try {
    return { success: true, data: mockVehicleDispatchStats };
  } catch (error) {
    console.error('[VehicleDispatchActions] getVehicleDispatchStats error:', error);
    return { success: false, error: '서버 오류가 발생했습니다.' };
  }
}

// ===== 배차차량 상세 조회 =====
export async function getVehicleDispatchById(id: string): Promise<{
  success: boolean;
  data?: VehicleDispatchDetail;
  error?: string;
}> {
  try {
    // Mock: ID로 목록에서 찾아서 상세 데이터 생성
    const item = mockVehicleDispatchItems.find((i) => i.id === id);
    if (!item) {
      // fallback으로 기본 상세 데이터 반환
      return { success: true, data: { ...mockVehicleDispatchDetail, id } };
    }

    const detail: VehicleDispatchDetail = {
      id: item.id,
      dispatchNo: item.dispatchNo,
      shipmentNo: item.shipmentNo,
      siteName: item.siteName,
      orderCustomer: item.orderCustomer,
      freightCostType: item.freightCostType,
      status: item.status,
      writer: item.writer,
      logisticsCompany: item.logisticsCompany,
      arrivalDateTime: item.arrivalDateTime,
      tonnage: item.tonnage,
      vehicleNo: item.vehicleNo,
      driverContact: item.driverContact,
      remarks: item.remarks,
      supplyAmount: item.supplyAmount,
      vat: item.vat,
      totalAmount: item.totalAmount,
    };

    return { success: true, data: detail };
  } catch (error) {
    console.error('[VehicleDispatchActions] getVehicleDispatchById error:', error);
    return { success: false, error: '서버 오류가 발생했습니다.' };
  }
}

// ===== 배차차량 수정 =====
export async function updateVehicleDispatch(
  id: string,
  _data: VehicleDispatchEditFormData
): Promise<{ success: boolean; error?: string }> {
  try {
    // Mock: 항상 성공 반환
    return { success: true };
  } catch (error) {
    console.error('[VehicleDispatchActions] updateVehicleDispatch error:', error);
    return { success: false, error: '서버 오류가 발생했습니다.' };
  }
}
