import {
  httpGetRequest,
  httpPostRequest,
  httpPutRequest,
  httpDeleteRequest,
  APIUrlGenerator,
} from "@/utils/baseHttpService";
import { API_ROUTES } from "@/constant/routes";
import {
  Category,
  CreateCategoryRequest,
  UpdateCategoryRequest,
  CategoriesResponse,
  CategoryResponse,
  CreateCategoryResponse,
  UpdateCategoryResponse,
  DeleteCategoryResponse,
  CategoryFilters,
} from "./_models";

export const getCategories = async (filters?: CategoryFilters) => {
  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<CategoriesResponse>(
      APIUrlGenerator(API_ROUTES.GET_CATEGORIES, queryParams, undefined, false)
    );

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

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

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

export const getCategory = async (id: string) => {
  const response = await httpGetRequest<CategoryResponse>(
    APIUrlGenerator(API_ROUTES.GET_CATEGORY(id), undefined, undefined, false)
  );
  return response.data.category;
};

export const createCategory = async (data: CreateCategoryRequest) => {
  const response = await httpPostRequest<CreateCategoryResponse>(
    APIUrlGenerator(API_ROUTES.CREATE_CATEGORY, undefined, undefined, false),
    data
  );
  return response.data.category;
};

export const updateCategory = async (data: UpdateCategoryRequest) => {
  const response = await httpPutRequest<UpdateCategoryResponse>(
    APIUrlGenerator(
      API_ROUTES.UPDATE_CATEGORY(data.id.toString()),
      undefined,
      undefined,
      false
    ),
    data
  );
  return response.data.category;
};

export const deleteCategory = async (id: string) => {
  const response = await httpDeleteRequest<DeleteCategoryResponse>(
    APIUrlGenerator(API_ROUTES.DELETE_CATEGORY(id), undefined, undefined, false)
  );
  return response.data;
};
