import { apiSlice } from "../..";
import URLS from "../../constants";
import { generateQueryString } from "@/utils/queryStringUtil";

export interface SubCategory {
  id: string;
  name: string;
  categoryId?: { id?: string, name?: string };
  createdBy?: string;
  updatedBy?: string;
}

interface GetSubCategoryListResponse {
  data: {
    results: SubCategory[];
    page: number;
    limit: number;
    totalPages: number;
    totalResults: number;
  };
  code: number;
  message: string;
  success: boolean;
  error?: object;
}

interface GetSubCategoryByIdResponse {
  data: SubCategory;
  code: number;
  message: string;
  success: boolean;
  error?: object;
}

export const subCategoryApi = apiSlice.injectEndpoints({
  endpoints: (builder) => ({
    getSubCategories: builder.query<
      GetSubCategoryListResponse,
      { page?: number; limit?: number; search?: string; populate?: string; categoryId?:string; sortBy?:string }
    >({
      query: (params) => ({
        url: `${URLS.SUB_CATEGORY}?${generateQueryString(
          params as Record<string, unknown>
        )}`,
        method: "GET",
      }),
      providesTags: ["SubCategory"],
    }),

    getSubCategoryById: builder.query<GetSubCategoryByIdResponse, string>({
      query: (id) => ({
        url: `${URLS.SUB_CATEGORY}/${id}`,
        method: "GET",
      }),
    }),

    createSubCategory: builder.mutation<
      SubCategory,
      { name: string; categoryId: string }
    >({
      query: (body) => ({
        url: `${URLS.SUB_CATEGORY}`,
        method: "POST",
        body,
      }),
      invalidatesTags: ["SubCategory"],
    }),

    updateSubCategory: builder.mutation<
      SubCategory,
      { id: string; name: string; categoryId?: string }
    >({
      query: ({ id, ...body }) => ({
        url: `${URLS.SUB_CATEGORY}/${id}`,
        method: "PATCH",
        body,
      }),
      invalidatesTags: ["SubCategory"],
    }),

    deleteSubCategory: builder.mutation<{ success: boolean }, string>({
      query: (id) => ({
        url: `${URLS.SUB_CATEGORY}/${id}`,
        method: "DELETE",
      }),
      invalidatesTags: ["SubCategory"],
    }),
  }),
  overrideExisting: false,
});

export const {
  useGetSubCategoriesQuery,
  useGetSubCategoryByIdQuery,
  useCreateSubCategoryMutation,
  useUpdateSubCategoryMutation,
  useDeleteSubCategoryMutation,
} = subCategoryApi;
