"use server";

import { serverFetchJson } from "../../utils/fetchUtil";
import { BASE_API_URL } from "../../../config/api";

export interface LogisticRow {
  id: number;
  logisticName: string;
  carPlate: string;
  driverName: string;
  driverNumber: number;
}

export type SaveLogisticRequest = {
  id?: number | null;
  logisticName: string;
  carPlate: string;
  driverName: string;
  driverNumber: number;
};

export const findAllLogisticsAction = async (): Promise<LogisticRow[]> => {
  const endpoint = `${BASE_API_URL}/logistic/all`;
  return serverFetchJson<LogisticRow[]>(endpoint, {
    method: "GET",
    headers: { "Content-Type": "application/json" },
  });
};

export const saveLogisticAction = async (
  data: SaveLogisticRequest,
): Promise<LogisticRow> => {
  const endpoint = `${BASE_API_URL}/logistic/save`;
  return serverFetchJson<LogisticRow>(endpoint, {
    method: "POST",
    body: JSON.stringify(data),
    headers: { "Content-Type": "application/json" },
  });
};

export const saveLogisticsBatchCreateAction = async (
  items: Omit<SaveLogisticRequest, "id">[],
): Promise<LogisticRow[]> => {
  const endpoint = `${BASE_API_URL}/logistic/save-batch`;
  return serverFetchJson<LogisticRow[]>(endpoint, {
    method: "POST",
    body: JSON.stringify({ items }),
    headers: { "Content-Type": "application/json" },
  });
};

export type DeleteLogisticRequest = {
  id: number;
};

export const deleteLogisticAction = async (
  data: DeleteLogisticRequest,
): Promise<{ message?: string }> => {
  const endpoint = `${BASE_API_URL}/logistic/delete`;
  return serverFetchJson<{ message?: string }>(endpoint, {
    method: "POST",
    body: JSON.stringify(data),
    headers: { "Content-Type": "application/json" },
  });
};
