import {
  CANCEL_ORDER_URL,
  CREATE_ORDER_URL,
  ORDER_DETAILS_URL,
  ORDERS_URL,
  PRODUCTS_AND_CATEGORIES_URL,
  RESTAURANT_DETAILS_URL,
  TABLES_URL,
} from "utils/constants";

import { OrderDetails } from "pages/checkout/hooks/types";
import menuParser from "pages/menu/helper";
import { RestaurantDetails } from "utils/types/appTypes";
import { baseApi } from "./apiSlice";

export const branchApi = baseApi.injectEndpoints({
  endpoints: (builder) => ({
    getRestaurantDetails: builder.query<RestaurantDetails, string | void>({
      query: (restaurantSubdomain: string) => ({
        url: RESTAURANT_DETAILS_URL,
        method: "POST",
        body: {
          subdomain: restaurantSubdomain,
        },
      }),
      transformResponse: (response: any) => {
        return response?.result?.restaurants?.[0];
      },
      providesTags: ["Restaurant"],
    }),
    getMenu: builder.query<any, string | void>({
      query: (restaurantId: string) =>
        `${PRODUCTS_AND_CATEGORIES_URL}${restaurantId}`,
      transformResponse: (response: any) => {
        return menuParser(response);
      },
    }),
    getOrders: builder.query<any, void>({
      query: () => ({
        url: ORDERS_URL,
        method: "POST",
      }),
      transformResponse: (response: any) => {
        return response.result.data.orders;
      },
      providesTags: ["Orders"],
    }),
    createOrder: builder.mutation({
      query: (body: any) => ({
        url: CREATE_ORDER_URL,
        method: "POST",
        body,
      }),
      invalidatesTags: ["Orders", "Restaurant"],
    }),
    cancelOrder: builder.mutation({
      query: (body: any) => ({
        url: CANCEL_ORDER_URL,
        method: "POST",
        body,
      }),
      invalidatesTags: ["Orders", "Restaurant"],
    }),
    getTables: builder.query<any, { restaurantID: string; tableType: string }>({
      query: ({
        restaurantID,
        tableType,
      }: {
        restaurantID: string;
        tableType: string;
      }) => ({
        url: TABLES_URL,
        method: "POST",
        body: {
          restaurantID,
          tableType,
        },
      }),
      transformResponse: (response: any) => {
        return response.result.data;
      },
    }),
    getOrderDetails: builder.query<
      OrderDetails,
      { orderID: string; restaurantID: string }
    >({
      query: ({
        orderID,
        restaurantID,
      }: {
        orderID: string;
        restaurantID: string;
      }) => ({
        url: `${ORDER_DETAILS_URL}/${orderID}`,
        method: "POST",
        body: {
          restaurantID,
        },
      }),
      transformResponse: (response: any) => {
        return response.result;
      },
    }),
  }),
});
export const {
  useGetRestaurantDetailsQuery,
  useGetMenuQuery,
  useCreateOrderMutation,
  useGetOrdersQuery,
  useGetTablesQuery,
  useGetOrderDetailsQuery,
  useCancelOrderMutation,
} = branchApi;
