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

export const appointmentsApi = createApi({
    reducerPath: 'appointmentsApi',
    baseQuery: fetchBaseQuery({
        baseUrl: CONFIG.BASE_URL,
        prepareHeaders: (headers) => {
            const token = localStorage.getItem('access_token');
            if (token) headers.set('Authorization', `Bearer ${token}`);
            return headers;
        },
    }),
    tagTypes: ['Appointment'],
    endpoints: (builder) => ({
        getAppointments: builder.query({
            query: () => '/appointments/',
            providesTags: ['Appointment'],
            refetchOnMountOrArgChange: 5,
        }),
        getByPatientId: builder.query({
            query: (id) => `/appointments/patient/${id}/`,
            providesTags: ['Appointment'],
            refetchOnMountOrArgChange: 5,
        }),
        createAppointment: builder.mutation({
            query: (data) => ({
                url: '/appointments/',
                method: 'POST',
                body: data,
            }),
            invalidatesTags: ['Appointment'],
        }),
        updateAppointment: builder.mutation({
            query: ({ id, data }) => ({
                url: `/appointments/${id}/`,
                method: 'PUT',
                body: data,
            }),
            invalidatesTags: ['Appointment'],
        }),
    }),
});

export const {
    useGetAppointmentsQuery,
    useGetByPatientIdQuery,
    useCreateAppointmentMutation,
    useUpdateAppointmentMutation,
} = appointmentsApi;