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

export interface PushNotification {
  id: string;
  title: string;
  description: string;
  image?: string;
  type: string;
  receivedTo: { id: string };
  read: boolean;
  createdBy?: { id: string };
  updatedBy?: { id: string };
}

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

interface UpdatePushNotificationBody {
  read: boolean;
}

interface BulkUpdatePushNotificationBody {
  read: boolean;
}

export const pushNotificationApi = apiSlice.injectEndpoints({
  endpoints: (builder) => ({
    getPushNotifications: builder.query<
      GetPushNotificationListResponse,
      { search?: string; read?: boolean; page?: number }
    >({
      query: (params) => ({
        url: `${URLS.PUSH_NOTIFICATION}?${generateQueryString(
          params as Record<string, unknown>
        )}`,
        method: "GET",
      }),
      providesTags: ["PushNotification"],
    }),

    updatePushNotification: builder.mutation<
      PushNotification,
      { id: string; body: UpdatePushNotificationBody }
    >({
      query: ({ id, body }) => ({
        url: `${URLS.PUSH_NOTIFICATION}/${id}`,
        method: "PATCH",
        body,
      }),
      invalidatesTags: ["PushNotification"],
    }),

    bulkUpdatePushNotification: builder.mutation<
      { success: boolean },
      BulkUpdatePushNotificationBody
    >({
      query: (body) => ({
        url: `${URLS.PUSH_NOTIFICATION}/bulk-update`,
        method: "PATCH",
        body,
      }),
      invalidatesTags: ["PushNotification"],
    }),
  }),
  overrideExisting: false,
});

export const {
  useGetPushNotificationsQuery,
  useUpdatePushNotificationMutation,
  useBulkUpdatePushNotificationMutation,
} = pushNotificationApi;
