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

export const patientsApi = createApi({
    reducerPath: 'patientsApi',
    baseQuery: baseQueryWithAuth,
    tagTypes: ['Patient'],
    endpoints: (builder) => ({
        getPatients: builder.query({
            query: ({ page, pageSize, search, sortOrder }) => ({
                url: '/patients/',
                params: {
                    page,
                    page_size: pageSize,
                    search: search || undefined,
                    sort_order: sortOrder || undefined,
                },
            }),
            providesTags: ['Patients'],
        }),
        getAllPatients: builder.query({
            query: () => ({
                url: '/patients/',
                params: { all_params: true },
            }),
            providesTags: ['Patients'],
            transformResponse: (response) => {
                if (!response || !Array.isArray(response.patients)) {
                    console.warn('Unexpected patients API response:', response);
                    return [];
                }
                return response.patients;
            },
        }),
        addPatient: builder.mutation({
            query: (patient) => ({
                url: '/patients/',
                method: 'POST',
                body: patient
            }),
            invalidatesTags: ['Patients']
        }),
        updatePatient: builder.mutation({
            query: ({id, ...patient}) => ({
                url: `/patients/${id}/`,
                method: 'PUT',
                body: patient
            }),
            invalidatesTags: ['Patients']
        }),
        deletePatient: builder.mutation({
            query: (id) => ({
                url: `/patients/${id}/`,
                method: 'DELETE'
            }),
            invalidatesTags: ['Patients']
        }),
    }),
});

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