import {createApi, fetchBaseQuery} from '@reduxjs/toolkit/query/react'
import CONFIG from "../Core/сonfig.js";

export const setsApi = createApi({
    reducerPath: 'setsApi',
    baseQuery: fetchBaseQuery({
        baseUrl: CONFIG.BASE_URL,
        prepareHeaders: (headers) => {
            const token = localStorage.getItem('access_token');
            if (token) headers.set('Authorization', `Bearer ${token}`);
            return headers;
        }
    }),
    tagTypes: ['Set'],
    endpoints: (builder) => ({
        getSets: builder.query({
            query: () => '/sets/',
            providesTags: ['Set'],
            refetchOnMountOrArgChange: 5
        }),
        addSet: builder.mutation({
            query: (set) => ({
                url: '/sets/',
                method: 'POST',
                body: set
            }),
            invalidatesTags: ['Set']
        }),
        updateSet: builder.mutation({
            query: ({id, ...set}) => ({
                url: `/sets/${id}/`,
                method: 'PUT',
                body: set
            }),
            invalidatesTags: ['Set']
        }),
        deleteSet: builder.mutation({
            query: (id) => ({
                url: `/sets/${id}/`,
                method: 'DELETE'
            }),
            invalidatesTags: ['Set']
        }),
        appendLensesFromSet: builder.mutation({
            query: (id) => ({
                url: `/sets/append_lenses/${id}/`,
                method: 'POST',
            }),
            invalidatesTags: ['Set']
        }),
    }),
});

export const {
    useGetSetsQuery,
    useAddSetMutation,
    useUpdateSetMutation,
    useDeleteSetMutation,
    useAppendLensesFromSetMutation,
} = setsApi;