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

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

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

interface GetStateByIdResponse {
  data: State;
  code: number;
  message: string;
  success: boolean;
  error?: object;
}

export const stateApi = apiSlice.injectEndpoints({
  endpoints: (builder) => ({
    getStates: builder.query<
      GetStateListResponse,
      { page?: number; limit?: number; search?: string; populate?: string; country?: string; sortBy?: string }
    >({
      query: (params) => ({
        url: `${URLS.STATE}?${generateQueryString(params as Record<string, unknown>)}`,
        method: 'GET',
      }),
      providesTags: ['State'],
    }),

    getStateById: builder.query<GetStateByIdResponse, string>({
      query: (id) => ({
        url: `${URLS.STATE}/${id}`,
        method: 'GET',
      }),
    }),

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

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

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

export const {
  useGetStatesQuery,
  useGetStateByIdQuery,
  useCreateStateMutation,
  useUpdateStateMutation,
  useDeleteStateMutation,
} = stateApi;
