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

export interface City {
  id: string;
  name: string;
  state: {id?: string, name?: string};
  createdBy?: string;
  updatedBy?: string;
  loc: {
    type: 'Point';
    coordinates: [number, number]; // [longitude, latitude]
  };
}

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

interface GetCityByIdResponse {
  data: City;
  code: number;
  message: string;
  success: boolean;
  error?: object;
}

export const cityApi = apiSlice.injectEndpoints({
  endpoints: (builder) => ({
    getCities: builder.query<GetCityListResponse, { page?: number; limit?: number; search?: string; populate?: string; state?: string; sortBy?: string; withPropertiesOnly?: boolean }>({
      query: (params) => ({
        url: `${URLS.CITY}?${generateQueryString(params as Record<string, unknown>)}`,
        method: 'GET',
      }),
      providesTags: ['City'],
    }),

    getCityById: builder.query<GetCityByIdResponse, string>({
      query: (id) => ({
        url: `${URLS.CITY}/${id}`,
        method: 'GET',
      }),
    }),

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

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

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

export const {
  useGetCitiesQuery,
  useGetCityByIdQuery,
  useCreateCityMutation,
  useUpdateCityMutation,
  useDeleteCityMutation,
} = cityApi;
