// src/features/categories/categoryAPI.js
import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";

export const categoryApi = createApi({
  reducerPath: "categoryApi",
  baseQuery: fetchBaseQuery({
    baseUrl: import.meta.env.VITE_API_URL || "http://localhost:3000/api",
    prepareHeaders: (headers, { getState }) => {
      const token = getState().auth?.token;
      if (token) headers.set("Authorization", `Bearer ${token}`);
      return headers;
    },
  }),
  tagTypes: ["Categories"],
  endpoints: (builder) => ({
    getCategoryTree: builder.query({
      query: () => "/admin/tree",
      providesTags: ["Categories"],
    }),

    addCategory: builder.mutation({
  query: (formData) => ({
    url: "/admin/categories",
    method: "POST",
    body: formData,   // must be FormData
  }),
  invalidatesTags: ["Categories"],
}),

    // updateCategory: builder.mutation({
    //   query: ({ id, ...body }) => ({
    //     url: `/admin/categories/${id}`,
    //     method: "PUT",
    //     body,
    //   }),
    //   invalidatesTags: ["Categories"],
    // }),

    updateCategory: builder.mutation({
      query: ({ id, data }) => ({
        url: `/admin/categories/${id}`,
        method: "PUT",
        body: data, // can be FormData OR JSON
      }),
      invalidatesTags: ["Categories"],
    }),

    getCategoryById: builder.query({
      query: (id) => `/admin/categories/${id}`,
    }),

    updateCategoryStatus: builder.mutation({
      query: ({ id, isActive }) => ({
        url: `/admin/categories/${id}/status`,
        method: "PATCH",
        body: { isActive },
      }),
      invalidatesTags: ["Categories"],
    }),

    deleteCategory: builder.mutation({
      query: (id) => ({
        url: `/admin/categories/${id}`,
        method: "DELETE",
      }),
      invalidatesTags: ["Categories"],
    }),

    reorderCategories: builder.mutation({
      query: (orders) => ({
        url: "/admin/categories/reorder",
        method: "PATCH",
        body: { orders },
      }),
      invalidatesTags: ["Categories"],
    }),
  }),
});

export const {
  useGetCategoryTreeQuery,
  useAddCategoryMutation,
  useUpdateCategoryMutation,
  useDeleteCategoryMutation,
  useGetCategoryByIdQuery,
  useUpdateCategoryStatusMutation,
  useReorderCategoriesMutation,
} = categoryApi;

export default categoryApi;
