import {
  httpGetRequest,
  httpPostRequest,
  httpPutRequest,
  httpDeleteRequest,
  APIUrlGenerator,
} from "@/utils/baseHttpService";
import { API_ROUTES } from "@/constant/routes";
import {
  CreateShippingMethodRequest,
  UpdateShippingMethodRequest,
  PaginatedShippingMethodsResponse,
  ShippingMethod,
} from "./_models";

export const getShippingMethods = async () => {
  const response = await httpGetRequest<PaginatedShippingMethodsResponse>(
    APIUrlGenerator(API_ROUTES.GET_SHIPPING_METHODS)
  );
  if (Array.isArray(response.data)) {
    return response.data;
  }
  return response.data?.shipping_methods || [];
};

export const getShippingMethod = async (id: string) => {
  const response = await httpGetRequest<any>(
    APIUrlGenerator(API_ROUTES.GET_SHIPPING_METHOD(id))
  );
  const payload = response.data as any;
  // Support either plain object or wrapped { shipping_method: { ... } }
  return (payload?.shipping_method || payload) as ShippingMethod;
};

export const createShippingMethod = async (
  payload: CreateShippingMethodRequest
) => {
  const response = await httpPostRequest<ShippingMethod>(
    APIUrlGenerator(API_ROUTES.CREATE_SHIPPING_METHOD),
    payload
  );
  return response.data;
};

export const updateShippingMethod = async (
  id: string,
  payload: UpdateShippingMethodRequest
) => {
  const response = await httpPutRequest<ShippingMethod>(
    APIUrlGenerator(API_ROUTES.UPDATE_SHIPPING_METHOD(id)),
    payload
  );
  return response.data;
};

export const deleteShippingMethod = async (id: string) => {
  const response = await httpDeleteRequest<{ message: string }>(
    APIUrlGenerator(API_ROUTES.DELETE_SHIPPING_METHOD(id))
  );
  return response.data;
};
