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

export interface PropertyConfiguration {
  id: string;
  name: string;
  category?: { id?: string; name?: string };
  subCategory?: { id?: string; name?: string };
  createdBy?: string;
  updatedBy?: string;
}

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

export const propertyConfigurationApi = apiSlice.injectEndpoints({
  endpoints: (builder) => ({
    getPropertyConfigurations: builder.query<
      GetPropertyConfigurationListResponse,
      {
        page?: number;
        limit?: number;
        search?: string;
        populate?: string;
        categoryId?: string;
        subCategoryId?: string;
      }
    >({
      query: (params) => ({
        url: `${URLS.PROPERTY_CONFIGURATION}?${generateQueryString(
          params as Record<string, unknown>
        )}`,
        method: "GET",
      }),
      providesTags: ["PropertyConfiguration"],
    }),

    createPropertyConfiguration: builder.mutation<
      PropertyConfiguration,
      { name: string; category: string; subCategory: string }
    >({
      query: (body) => ({
        url: `${URLS.PROPERTY_CONFIGURATION}`,
        method: "POST",
        body,
      }),
      invalidatesTags: ["PropertyConfiguration"],
    }),

    updatePropertyConfiguration: builder.mutation<
      PropertyConfiguration,
      { id: string; name: string; category?: string; subCategory?: string }
    >({
      query: ({ id, ...body }) => ({
        url: `${URLS.PROPERTY_CONFIGURATION}/${id}`,
        method: "PATCH",
        body,
      }),
      invalidatesTags: ["PropertyConfiguration"],
    }),

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

export const {
  useGetPropertyConfigurationsQuery,
  useCreatePropertyConfigurationMutation,
  useUpdatePropertyConfigurationMutation,
  useDeletePropertyConfigurationMutation,
} = propertyConfigurationApi;
