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

export interface Country {
  id: string;
  name: string;
  createdBy?: string;
  updatedBy?: string;
  loc: {
    type: string;
    coordinates: [number, number];
  };
}

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

interface GetCountryByIdResponse {
  data: Country;
  code: number;
  message: string;
  success: boolean;
  error?: object;
}

export const countryApi = apiSlice.injectEndpoints({
  endpoints: (builder) => ({
    getCountries: builder.query<
      GetCountryListResponse,
      { page?: number; limit?: number; search?: string; sortBy?: string; }
    >({
      query: (params) => ({
        url: `${URLS.COUNTRY}?${generateQueryString(params as Record<string, unknown>)}`,
        method: 'GET',
      }),
      providesTags: ['Country'],
    }),

    getCountryById: builder.query<GetCountryByIdResponse, string>({
      query: (id) => ({
        url: `${URLS.COUNTRY}/${id}`,
        method: 'GET',
      }),
    }),

    createCountry: builder.mutation<
      Country,
      {
        name: string;
        loc: {
          type: 'Point';
          coordinates: [number, number];
        };
      }
    >({
      query: (body) => ({
        url: `${URLS.COUNTRY}`,
        method: 'POST',
        body,
      }),
      invalidatesTags: ['Country'],
    }),

    updateCountry: builder.mutation<
      Country,
      {
        id: string;
        name: string;
        loc: {
          type: 'Point';
          coordinates: [number, number];
        };
      }
    >({
      query: ({ id, ...body }) => ({
        url: `${URLS.COUNTRY}/${id}`,
        method: 'PATCH',
        body,
      }),
      invalidatesTags: ['Country'],
    }),

    deleteCountry: builder.mutation<{ success: boolean }, string>({
      query: (id) => ({
        url: `${URLS.COUNTRY}/${id}`,
        method: 'DELETE',
      }),
      invalidatesTags: ['Country'],
    }),
  }),
});

export const {
  useGetCountriesQuery,
  useGetCountryByIdQuery,
  useCreateCountryMutation,
  useUpdateCountryMutation,
  useDeleteCountryMutation,
} = countryApi;
