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


export const lensesApi = createApi({
    reducerPath: 'lensesApi',
    baseQuery: fetchBaseQuery({
        baseUrl: CONFIG.BASE_URL,
        prepareHeaders: (headers) => {
            const token = localStorage.getItem('access_token');
            if (token) headers.set('Authorization', `Bearer ${token}`);
            return headers;
        }
    }),
    tagTypes: ['Lens'],
    endpoints: (builder) => ({
        getLenses: builder.query({
            query: () => '/lenses/',
            providesTags: ['Lens'],
            refetchOnMountOrArgChange: 5
        }),
        getNotIssuedLenses: builder.query({
            query: () => '/lenses/not_issued/',
            providesTags: ['Lens'],
            refetchOnMountOrArgChange: 5
        }),
        addLens: builder.mutation({
            query: (lens) => ({
                url: '/lenses/',
                method: 'POST',
                body: lens
            }),
            invalidatesTags: ['Lens']
        }),
        updateLens: builder.mutation({
            query: ({ id, ...lens }) => ({
                url: `/lenses/${id}/`,
                method: 'PUT',
                body: lens
            }),
            invalidatesTags: ['Lens']
        }),
        deleteLens: builder.mutation({
            query: (id) => ({
                url: `/lenses/${id}/`,
                method: 'DELETE'
            }),
            invalidatesTags: ['Lens']
        }),
    }),
});

export const {
    useGetLensesQuery,
    useGetNotIssuedLensesQuery,
    useAddLensMutation,
    useUpdateLensMutation,
    useDeleteLensMutation,
} = lensesApi;