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


export const lensesApi = createApi({
    reducerPath: 'lensesApi',
    baseQuery: baseQueryWithAuth,
    tagTypes: ['Lens'],
    endpoints: (builder) => ({
        getLenses: builder.query({
            query: ({page, pageSize, search, sortOrder, searchParams}) => ({
                url: '/lenses/',
                params: {
                    page,
                    page_size: pageSize,
                    search: search || undefined,
                    sort_order: sortOrder || undefined,
                    tor: searchParams.tor || undefined,
                    diameter: searchParams.diameter || undefined,
                    preset_refraction: searchParams.preset_refraction || undefined,
                    periphery_toricity: searchParams.periphery_toricity || undefined,
                    side: searchParams.side !== 'all' ? searchParams.side : undefined,
                    issued: searchParams.issued !== 'all' ? searchParams.issued : undefined,
                    trial: searchParams.trial || undefined,
                },
            }),
            providesTags: ['Lenses'],
            transformResponse: (response) => {
                if (!response || !Array.isArray(response.lenses)) {
                    console.warn('Unexpected lenses API response:', response);
                    return {lenses: [], total_count: 0};
                }
                return response;
            },
        }),
        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;