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

export const patientsApi = createApi({
    reducerPath: 'patientsApi',
    baseQuery: fetchBaseQuery({
        baseUrl: CONFIG.BASE_URL,
        prepareHeaders: (headers) => {
            const token = localStorage.getItem('access_token');
            if (token) headers.set('Authorization', `Bearer ${token}`);
            return headers;
        }
    }),
    tagTypes: ['Patient'],
    endpoints: (builder) => ({
        getPatients: builder.query({
            query: () => '/patients/',
            providesTags: ['Patient'],
            refetchOnMountOrArgChange: 5
        }),
        addPatient: builder.mutation({
            query: (patient) => ({
                url: '/patients/',
                method: 'POST',
                body: patient
            }),
            invalidatesTags: ['Patient']
        }),
        updatePatient: builder.mutation({
            query: ({id, ...patient}) => ({
                url: `/patients/${id}/`,
                method: 'PUT',
                body: patient
            }),
            invalidatesTags: ['Patient']
        }),
        deletePatient: builder.mutation({
            query: (id) => ({
                url: `/patients/${id}/`,
                method: 'DELETE'
            }),
            invalidatesTags: ['Patient']
        }),
    }),
});

export const {
    useGetPatientsQuery,
    useAddPatientMutation,
    useUpdatePatientMutation,
    useDeletePatientMutation,
} = patientsApi;