import {
  APIUrlGenerator,
  httpGetRequest,
  httpPostRequest,
  httpPutRequest,
  httpDeleteRequest,
} from "@/utils/baseHttpService";
import { API_ROUTES } from "@/constant/routes";
import {
  CreateDiscountCodeRequest,
  UpdateDiscountCodeRequest,
  DiscountCode,
  DiscountCodeFilters,
  PaginatedDiscountCodesResponse,
} from "./_models";

export const getDiscountCodes = async (filters?: DiscountCodeFilters) => {
  const queryParams: Record<string, string | number | null> = {};

  if (filters?.page) queryParams.page = filters.page;
  if (filters?.limit) queryParams.limit = filters.limit;
  if (filters?.status) queryParams.status = filters.status;
  if (filters?.type) queryParams.type = filters.type;
  if (filters?.application_level) {
    if (Array.isArray(filters.application_level)) {
      if (filters.application_level.length > 0) {
        queryParams.application_level = filters.application_level.join(",");
      }
    } else {
      queryParams.application_level = filters.application_level;
    }
  }
  if (filters?.code) queryParams.code = filters.code;
  if (typeof filters?.active_only === "boolean")
    queryParams.active_only = filters.active_only ? "true" : "false";

  const response = await httpGetRequest<PaginatedDiscountCodesResponse>(
    APIUrlGenerator(API_ROUTES.GET_DISCOUNT_CODES, queryParams)
  );

  return response.data.discount_codes || [];
};

export const getDiscountCode = async (id: string) => {
  const response = await httpGetRequest<DiscountCode>(
    APIUrlGenerator(API_ROUTES.GET_DISCOUNT_CODE(id))
  );
  return response.data as unknown as DiscountCode;
};

export const createDiscountCode = async (
  payload: CreateDiscountCodeRequest
) => {
  const response = await httpPostRequest<DiscountCode>(
    APIUrlGenerator(API_ROUTES.CREATE_DISCOUNT_CODE),
    payload
  );
  return response.data;
};

export const updateDiscountCode = async (
  id: string,
  payload: UpdateDiscountCodeRequest
) => {
  const response = await httpPutRequest<DiscountCode>(
    APIUrlGenerator(API_ROUTES.UPDATE_DISCOUNT_CODE(id)),
    payload
  );
  return response.data;
};

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