import {createApi} from "@reduxjs/toolkit/query/react";
import {baseQueryWithAuth} from "./baseQuery.js";

export const appointmentFilesApi = createApi({
    reducerPath: 'appointmentFilesApi',
    baseQuery: baseQueryWithAuth,
    tagTypes: ['AppointmentFile'],
    endpoints: (builder) => ({
        getAppointmentFiles: builder.query({
            query: (appointmentId) => {
                return `/appointment_files/${appointmentId}/`;
            },
            providesTags: ['AppointmentFile'],
            refetchOnMountOrArgChange: 5,
        }),
        deleteAppointmentFile: builder.mutation({
            query: (fileId) => ({
                url: `/appointment_files/${fileId}/`,
                method: 'DELETE',
            }),
            invalidatesTags: ['AppointmentFile'],
        }),
        uploadAppointmentFile: builder.mutation({
            query: ({appointmentId, file}) => {
                if (!(file instanceof File)) {
                    throw new Error('Invalid file object');
                }
                const formData = new FormData();
                formData.append('file', file);
                return {
                    url: `/appointment_files/${appointmentId}/upload/`,
                    method: 'POST',
                    credentials: 'include',
                    formData: true,
                    body: formData,
                };
            },
            invalidatesTags: ['AppointmentFile'],
        }),
    }),
});

export const {
    useGetAppointmentFilesQuery,
    useDeleteAppointmentFileMutation,
    useUploadAppointmentFileMutation,
} = appointmentFilesApi;