'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 VehicleMaintenanceApi,
  type MaintenanceFormData,
  transformMaintenanceApi,
} from '../types';

// ===== 정비이력 목록 (페이지네이션) =====
export async function getVehicleMaintenances(params: {
  page?: number;
  perPage?: number;
  search?: string;
  vehicleId?: string;
  category?: string;
  startDate?: string;
  endDate?: string;
}) {
  return executePaginatedAction<VehicleMaintenanceApi, ReturnType<typeof transformMaintenanceApi>>({
    url: buildApiUrl('/api/v1/vehicle-maintenances', {
      page: params.page,
      per_page: params.perPage,
      search: params.search,
      vehicle_id: params.vehicleId !== 'all' ? params.vehicleId : undefined,
      category: params.category !== 'all' ? params.category : undefined,
      start_date: params.startDate,
      end_date: params.endDate,
    }),
    transform: transformMaintenanceApi,
    errorMessage: '정비이력 목록 조회에 실패했습니다.',
  });
}

// ===== 정비이력 단건 조회 =====
export async function getVehicleMaintenanceById(id: number) {
  return executeServerAction<VehicleMaintenanceApi, ReturnType<typeof transformMaintenanceApi>>({
    url: buildApiUrl(`/api/v1/vehicle-maintenances/${id}`),
    transform: transformMaintenanceApi,
    errorMessage: '정비이력 조회에 실패했습니다.',
  });
}

// ===== 정비이력 등록 =====
export async function createVehicleMaintenance(formData: MaintenanceFormData) {
  return executeServerAction({
    url: buildApiUrl('/api/v1/vehicle-maintenances'),
    method: 'POST',
    body: {
      vehicle_id: Number(formData.vehicleId),
      date: formData.date,
      category: formData.category,
      description: formData.description,
      amount: Number(formData.amount) || 0,
      mileage: Number(formData.mileage) || 0,
      vendor: formData.vendor || null,
      memo: formData.memo || null,
    },
    errorMessage: '정비이력 등록에 실패했습니다.',
  });
}

// ===== 정비이력 수정 =====
export async function updateVehicleMaintenance(id: number, formData: MaintenanceFormData) {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/vehicle-maintenances/${id}`),
    method: 'PUT',
    body: {
      vehicle_id: Number(formData.vehicleId),
      date: formData.date,
      category: formData.category,
      description: formData.description,
      amount: Number(formData.amount) || 0,
      mileage: Number(formData.mileage) || 0,
      vendor: formData.vendor || null,
      memo: formData.memo || null,
    },
    errorMessage: '정비이력 수정에 실패했습니다.',
  });
}

// ===== 정비이력 삭제 =====
export async function deleteVehicleMaintenance(id: number) {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/vehicle-maintenances/${id}`),
    method: 'DELETE',
    errorMessage: '정비이력 삭제에 실패했습니다.',
  });
}
