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

interface UserInfo {
  email: string;
  firstName: string;
  lastName: string;
  userType: string;
  phone: string;
}

interface CompanyInfo {
  name: string;
}
export interface Support {
  id: string;
  query: string;
  reply: string;
  status: string;
  createdAt: string;
  user: UserInfo;
  company: CompanyInfo;
  createdBy: string;
}

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

interface SupportRequestBody {
  query: string;
}

interface SupportReplyBody {
  reply: string;
}

export const supportApi = apiSlice.injectEndpoints({
  endpoints: (builder) => ({
    getSupports: builder.query<
      GetSupportListResponse,
      {
        page?: number;
        limit?: number;
        search?: string;
        status?: string;
        companyId?: string;
        userId?: string;
      }
    >({
      query: (params) => ({
        url: `${URLS.SUPPORT}?${generateQueryString(params as Record<string, unknown>)}`,
        method: 'GET',
      }),
      providesTags: ['Support'],
    }),

    createSupport: builder.mutation<Support, SupportRequestBody>({
      query: (body) => ({
        url: `${URLS.SUPPORT}`,
        method: 'POST',
        body,
      }),
      invalidatesTags: ['Support'],
    }),

    updateSupport: builder.mutation<Support, { id: string } & SupportReplyBody>({
      query: ({ id, ...body }) => ({
        url: `${URLS.SUPPORT}/${id}`,
        method: 'PATCH',
        body,
      }),
      invalidatesTags: ['Support'],
    }),
  }),
  overrideExisting: false,
});

export const {
  useGetSupportsQuery,
  useCreateSupportMutation,
  useUpdateSupportMutation,
} = supportApi;
