import { CategoryFormValues } from "../schemas/category";
import { PaginatedResponse } from "../types/api-response";
import { Category } from "../types/category";

import { apiHelpers } from "./api";

const categoryApi = {
  getCategories: async (
    params?: {
      search?: string;
      filter?: string | string[];
      limit?: number;
      offset?: number;
      sort?: string;
    },
    options?: { skipAuth?: boolean }
  ): Promise<PaginatedResponse<Category[]>> => {
    const filteredParams = { ...params };
    if (!filteredParams.sort) {
      delete filteredParams.sort;
    }

    return apiHelpers.get("/categories", {
      params: filteredParams,
      paramsSerializer: {
        indexes: null, // This allows multiple params with the same name
      },
      headers: options?.skipAuth ? { "X-Skip-Auth": "true" } : undefined,
    });
  },

  getCategoryById: async (id: string, options?: { skipAuth?: boolean }): Promise<Category> => {
    return apiHelpers.get(`/categories/${id}`, {
      headers: options?.skipAuth ? { "X-Skip-Auth": "true" } : undefined,
    });
  },

  deleteCategory: async (id?: string): Promise<Category> => {
    return apiHelpers.delete(`/categories/${id}`);
  },

  createCategory: async (category: Omit<CategoryFormValues, "id">): Promise<Category> => {
    return apiHelpers.post("/categories", category);
  },

  updateCategory: async (id: string, category: Partial<Category>): Promise<Category> => {
    return apiHelpers.patch(`/categories/${id}`, category);
  },
};

export default categoryApi;
