import { baseApi } from '@ema-platform/api';
import type {
  Location,
  LocationType,
  ListResponse,
  CreateLocationPayload,
  UpdateLocationPayload,
  CreateLocationTypePayload,
  UpdateLocationTypePayload,
} from '../types/location';

const locationApi = baseApi.injectEndpoints({
  endpoints: (builder) => ({
    getLocationTypes: builder.query<ListResponse<LocationType>, void>({
      query: () => '/location-types',
      providesTags: ['Api'],
    }),
    createLocationType: builder.mutation<LocationType, CreateLocationTypePayload>({
      query: (body) => ({ url: '/location-types', method: 'POST', body }),
      invalidatesTags: ['Api'],
    }),
    updateLocationType: builder.mutation<LocationType, UpdateLocationTypePayload>({
      query: ({ id, ...body }) => ({
        url: `/location-types/${id}`,
        method: 'PUT',
        body,
      }),
      invalidatesTags: ['Api'],
    }),
    deleteLocationType: builder.mutation<void, string>({
      query: (id) => ({ url: `/location-types/${id}`, method: 'DELETE' }),
      invalidatesTags: ['Api'],
    }),

    getLocations: builder.query<ListResponse<Location>, { parentId?: string; locationTypeId?: string; take?: number; skip?: number }>({
      query: (params) => ({ url: '/locations', params }),
      providesTags: ['Api'],
    }),
    createLocation: builder.mutation<Location, CreateLocationPayload>({
      query: (body) => ({ url: '/locations', method: 'POST', body }),
      invalidatesTags: ['Api'],
    }),
    updateLocation: builder.mutation<Location, UpdateLocationPayload>({
      query: ({ id, ...body }) => ({
        url: `/locations/${id}`,
        method: 'PUT',
        body,
      }),
      invalidatesTags: ['Api'],
    }),
    deleteLocation: builder.mutation<void, string>({
      query: (id) => ({ url: `/locations/${id}`, method: 'DELETE' }),
      invalidatesTags: ['Api'],
    }),
  }),
  overrideExisting: false,
});

export const {
  useGetLocationTypesQuery,
  useCreateLocationTypeMutation,
  useUpdateLocationTypeMutation,
  useDeleteLocationTypeMutation,
  useGetLocationsQuery,
  useCreateLocationMutation,
  useUpdateLocationMutation,
  useDeleteLocationMutation,
} = locationApi;
