import { baseApi } from "./baseApi"

export const filtersApi = baseApi.injectEndpoints({
  endpoints: (builder) => ({
    getFilters: builder.query({
      query: (params) => {
        const queryParams = new URLSearchParams()

        if (params?.category_id) {
          queryParams.append("category_id", String(params.category_id))
        }
        if (params?.collection_id) {
          queryParams.append("collection_id", String(params.collection_id))
        }
        if (params?.brand_id) {
          queryParams.append("brand_id", String(params.brand_id))
        }

        return `/filters?${queryParams.toString()}`
      },
      transformResponse: (response) => {
        return {
          categories: response.data?.categories || [],
          brands: response.data?.brands || [],
        }
      },
      keepUnusedDataFor: 300,
      
      serializeQueryArgs: ({ queryArgs }) => {
        if (!queryArgs) return 'no-params';
        
        const parts = [];
        
        if (queryArgs.category_id) {
          parts.push(`cat:${queryArgs.category_id}`);
        }
        if (queryArgs.collection_id) {
          parts.push(`col:${queryArgs.collection_id}`);
        }
        if (queryArgs.brand_id) {
          parts.push(`brd:${queryArgs.brand_id}`);
        }
        
        return parts.length > 0 ? parts.join('|') : 'no-params';
      },
      
      merge: (currentCache, newItems) => {
        return newItems;
      },
      
      refetchOnMountOrArgChange: 30, // Refetch if older than 30 seconds
      refetchOnFocus: false,
      refetchOnReconnect: false,
      
      providesTags: (result, error, arg) => {
        if (!arg) return [{ type: "Filters", id: "no-params" }];
        
        const tags = [{ type: "Filters", id: "LIST" }];
        
        if (arg.category_id) {
          tags.push({ type: "Filters", id: `cat-${arg.category_id}` });
        }
        if (arg.collection_id) {
          tags.push({ type: "Filters", id: `col-${arg.collection_id}` });
        }
        if (arg.brand_id) {
          tags.push({ type: "Filters", id: `brd-${arg.brand_id}` });
        }
        
        return tags;
      },
    }),
  }),
  overrideExisting: true,
})

export const { useGetFiltersQuery, useLazyGetFiltersQuery } = filtersApi