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

export interface Source {
  id: string;
  name: string;
  createdBy?: string;
  updatedBy?: string;
  isDefault: boolean;
}

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

interface GetSourceByIdResponse {
  data: Source;
  code: number;
  message: string;
  success: boolean;
  error?: object;
}

export const sourceApi = apiSlice.injectEndpoints({
  endpoints: (builder) => ({
    getSources: builder.query<
      GetSourceListResponse,
      { page?: number; limit?: number; search?: string; sortBy?: string; company?: string }
    >({
      query: (params) => ({
        url: `${URLS.SOURCE}?${generateQueryString(params as Record<string, unknown>)}`,
        method: 'GET',
      }),
      providesTags: ['Source'],
    }),

    getSourceById: builder.query<GetSourceByIdResponse, string>({
      query: (id) => ({
        url: `${URLS.SOURCE}/${id}`,
        method: 'GET',
      }),
    }),

    createSource: builder.mutation<Source, { name: string }>({
      query: (body) => ({
        url: `${URLS.SOURCE}`,
        method: 'POST',
        body,
      }),
      invalidatesTags: ['Source'],
    }),

    updateSource: builder.mutation<Source, { id: string; name: string }>({
      query: ({ id, ...body }) => ({
        url: `${URLS.SOURCE}/${id}`,
        method: 'PATCH',
        body,
      }),
      invalidatesTags: ['Source'],
    }),

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

export const {
  useGetSourcesQuery,
  useGetSourceByIdQuery,
  useCreateSourceMutation,
  useUpdateSourceMutation,
  useDeleteSourceMutation,
} = sourceApi;
