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

export const setContentApi = createApi({
    reducerPath: 'setContentApi',
    baseQuery: fetchBaseQuery({
        baseUrl: CONFIG.BASE_URL,
        prepareHeaders: (headers) => {
            const token = localStorage.getItem('access_token');
            if (token) headers.set('Authorization', `Bearer ${token}`);
            return headers;
        }
    }),
    tagTypes: ['SetContent'],
    endpoints: (builder) => ({
        getSetContent: builder.query({
            query: (setId) => `/set_content/${setId}/`,
            providesTags: ['SetContent'],
        }),
        addSetContent: builder.mutation({
            query: ({setId, setContent}) => ({
                url: `/set_content/${setId}/`,
                method: 'POST',
                body: setContent
            }),
            invalidatesTags: ['SetContent']
        }),
        updateSetContent: builder.mutation({
            query: ({setId, setContent}) => ({
                url: `/set_content/${setId}/`,
                method: 'PUT',
                body: setContent
            }),
            invalidatesTags: ['SetContent']
        }),
    }),
});

export const {
    useGetSetContentQuery,
    useAddSetContentMutation,
    useUpdateSetContentMutation,
} = setContentApi;