'use server';

import { buildApiUrl } from '@/lib/api/query-params';
import { executeServerAction } from '@/lib/api/execute-server-action';
import { executePaginatedAction } from '@/lib/api/execute-paginated-action';
import {
  type VehicleLogApi,
  type VehicleLogFormData,
  type VehicleLogSummary,
  transformVehicleLogApi,
} from '../types';

// ===== 운행기록 목록 (페이지네이션) =====
export async function getVehicleLogs(params: {
  page?: number;
  perPage?: number;
  search?: string;
  vehicleId?: string;
  year?: number;
  month?: number;
  tripType?: string;
}) {
  return executePaginatedAction<VehicleLogApi, ReturnType<typeof transformVehicleLogApi>>({
    url: buildApiUrl('/api/v1/vehicle-logs', {
      page: params.page,
      per_page: params.perPage,
      search: params.search,
      vehicle_id: params.vehicleId !== 'all' ? params.vehicleId : undefined,
      year: params.year,
      month: params.month,
      trip_type: params.tripType !== 'all' ? params.tripType : undefined,
    }),
    transform: transformVehicleLogApi,
    errorMessage: '운행기록 목록 조회에 실패했습니다.',
  });
}

// ===== 운행기록 단건 조회 =====
export async function getVehicleLogById(id: number) {
  return executeServerAction<VehicleLogApi, ReturnType<typeof transformVehicleLogApi>>({
    url: buildApiUrl(`/api/v1/vehicle-logs/${id}`),
    transform: transformVehicleLogApi,
    errorMessage: '운행기록 조회에 실패했습니다.',
  });
}

// ===== 운행기록 등록 =====
export async function createVehicleLog(formData: VehicleLogFormData) {
  return executeServerAction({
    url: buildApiUrl('/api/v1/vehicle-logs'),
    method: 'POST',
    body: {
      vehicle_id: Number(formData.vehicleId),
      log_date: formData.logDate,
      department: formData.department || null,
      driver_name: formData.driverName,
      trip_type: formData.tripType,
      departure_type: formData.departureType || null,
      departure_name: formData.departureName || null,
      departure_address: formData.departureAddress || null,
      arrival_type: formData.arrivalType || null,
      arrival_name: formData.arrivalName || null,
      arrival_address: formData.arrivalAddress || null,
      distance_km: Number(formData.distanceKm) || 0,
      note: formData.note || null,
    },
    errorMessage: '운행기록 등록에 실패했습니다.',
  });
}

// ===== 운행기록 수정 =====
export async function updateVehicleLog(id: number, formData: VehicleLogFormData) {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/vehicle-logs/${id}`),
    method: 'PUT',
    body: {
      vehicle_id: Number(formData.vehicleId),
      log_date: formData.logDate,
      department: formData.department || null,
      driver_name: formData.driverName,
      trip_type: formData.tripType,
      departure_type: formData.departureType || null,
      departure_name: formData.departureName || null,
      departure_address: formData.departureAddress || null,
      arrival_type: formData.arrivalType || null,
      arrival_name: formData.arrivalName || null,
      arrival_address: formData.arrivalAddress || null,
      distance_km: Number(formData.distanceKm) || 0,
      note: formData.note || null,
    },
    errorMessage: '운행기록 수정에 실패했습니다.',
  });
}

// ===== 운행기록 삭제 =====
export async function deleteVehicleLog(id: number) {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/vehicle-logs/${id}`),
    method: 'DELETE',
    errorMessage: '운행기록 삭제에 실패했습니다.',
  });
}

// ===== 월별 통계 =====
interface SummaryApi {
  total_distance: number;
  total_count: number;
  commute_to_distance: number;
  commute_to_count: number;
  commute_from_distance: number;
  commute_from_count: number;
  business_distance: number;
  business_count: number;
  personal_distance: number;
  personal_count: number;
}

export async function getVehicleLogSummary(params: {
  vehicleId?: string;
  year: number;
  month: number;
}) {
  return executeServerAction<SummaryApi, VehicleLogSummary>({
    url: buildApiUrl('/api/v1/vehicle-logs/summary', {
      vehicle_id: params.vehicleId !== 'all' ? params.vehicleId : undefined,
      year: params.year,
      month: params.month,
    }),
    transform: (api) => ({
      totalDistance: api.total_distance,
      totalCount: api.total_count,
      commuteToDistance: api.commute_to_distance,
      commuteToCount: api.commute_to_count,
      commuteFromDistance: api.commute_from_distance,
      commuteFromCount: api.commute_from_count,
      businessDistance: api.business_distance,
      businessCount: api.business_count,
      personalDistance: api.personal_distance,
      personalCount: api.personal_count,
    }),
    errorMessage: '운행 통계 조회에 실패했습니다.',
  });
}
