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

export interface Notification {
  id: string;
  title: string;
  description: string;
  image?: string;
  userType: 'builder' | 'broker' | 'all';
  device: 'ios' | 'android' | 'web' | 'all';
  status: 'send' | 'schedule';
  scheduleDateTime?: string | Date;
  createdBy?: { id: string };
  updatedBy?: { id: string };
}

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

interface GetNotificationByIdResponse {
  data: Notification;
  code: number;
  message: string;
  success: boolean;
  error?: object;
}

type GetNotificationQueryParams = {
  page?: number;
  limit?: number;
  search?: string;
  sortBy?: string;
  status?: string;
};

export const notificationApi = apiSlice.injectEndpoints({
  endpoints: (builder) => ({
    getNotifications: builder.query<GetNotificationListResponse, GetNotificationQueryParams>({
      query: (params) => ({
        url: `${URLS.NOTIFICATION}?${generateQueryString(params as Record<string, unknown>)}`,
        method: 'GET',
      }),
      providesTags: ['Notification'],
    }),

    getNotificationById: builder.query<GetNotificationByIdResponse, string>({
      query: (id) => ({
        url: `${URLS.NOTIFICATION}/${id}`,
        method: 'GET',
      }),
    }),

    createNotification: builder.mutation<Notification, Partial<Notification>>({
      query: (body) => ({
        url: `${URLS.NOTIFICATION}`,
        method: 'POST',
        body,
      }),
      invalidatesTags: ['Notification'],
    }),

    updateNotification: builder.mutation<Notification, { id: string } & Partial<Notification>>({
      query: ({ id, ...body }) => ({
        url: `${URLS.NOTIFICATION}/${id}`,
        method: 'PATCH',
        body,
      }),
      invalidatesTags: ['Notification'],
    }),

    deleteNotification: builder.mutation<{ success: boolean }, string>({
      query: (id) => ({
        url: `${URLS.NOTIFICATION}/${id}`,
        method: 'DELETE',
      }),
      invalidatesTags: ['Notification'],
    }),
  }),
  overrideExisting: false,
});

export const {
  useGetNotificationsQuery,
  useGetNotificationByIdQuery,
  useCreateNotificationMutation,
  useUpdateNotificationMutation,
  useDeleteNotificationMutation,
} = notificationApi;
