import {
  httpGetRequest,
  httpPostRequest,
  httpPutRequest,
  httpDeleteRequest,
  APIUrlGenerator,
} from "@/utils/baseHttpService";
import { API_ROUTES } from "@/constant/routes";
import {
  ProductOption,
  CreateProductOptionRequest,
  UpdateProductOptionRequest,
  ProductOptionsResponse,
  ProductOptionResponse,
  CreateProductOptionResponse,
  UpdateProductOptionResponse,
  DeleteProductOptionResponse,
  ProductOptionFilters,
} from "./_models";

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

    if (filters?.search) queryParams.search = filters.search;
    if (filters?.page) queryParams.page = filters.page;
    if (filters?.limit) queryParams.limit = filters.limit;

    const response = await httpGetRequest<ProductOptionsResponse>(
      APIUrlGenerator(API_ROUTES.GET_PRODUCT_OPTIONS, queryParams)
    );

    console.log("Product Options API Response:", response);

    if (
      response.data &&
      response.data.product_options &&
      Array.isArray(response.data.product_options)
    ) {
      return response.data.product_options;
    }

    console.warn("Product options is null or not an array:", response.data);
    return [];
  } catch (error) {
    console.error("Error fetching product options:", error);
    return [];
  }
};

export const getProductOption = async (id: string) => {
  const response = await httpGetRequest<ProductOptionResponse>(
    APIUrlGenerator(API_ROUTES.GET_PRODUCT_OPTION(id))
  );
  return response.data.product_option;
};

export const createProductOption = async (data: CreateProductOptionRequest) => {
  const response = await httpPostRequest<CreateProductOptionResponse>(
    APIUrlGenerator(API_ROUTES.CREATE_PRODUCT_OPTION),
    data
  );
  return response.data.product_option;
};

export const updateProductOption = async (data: UpdateProductOptionRequest) => {
  const response = await httpPutRequest<UpdateProductOptionResponse>(
    APIUrlGenerator(API_ROUTES.UPDATE_PRODUCT_OPTION(data.id.toString())),
    data
  );
  return response.data.product_option;
};

export const deleteProductOption = async (id: string) => {
  const response = await httpDeleteRequest<DeleteProductOptionResponse>(
    APIUrlGenerator(API_ROUTES.DELETE_PRODUCT_OPTION(id))
  );
  return response.data;
};
