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

export const lensIssuesApi = createApi({
    reducerPath: 'lensIssuesApi',
    baseQuery: baseQueryWithAuth,
    tagTypes: ['LensIssues'],
    endpoints: (builder) => ({
        getLensIssues: builder.query({
            query: ({ page, pageSize, search, sortOrder, startDate, endDate }) => ({
                url: '/lens_issues/',
                params: {
                    page,
                    page_size: pageSize,
                    search: search || undefined,
                    sort_order: sortOrder || undefined,
                    start_date: startDate || undefined,
                    end_date: endDate || undefined,
                },
            }),
            providesTags: ['LensIssues'],
            transformResponse: (response) => {
                if (!response) {
                    console.warn('Empty lens issues API response:', response);
                    return { issues: [], total_count: 0 };
                }
                if (Array.isArray(response.results) && typeof response.count === 'number') {
                    return { issues: response.results, total_count: response.count };
                }
                if (Array.isArray(response.issues) && typeof response.total_count === 'number') {
                    return response;
                }
                console.warn('Unexpected lens issues API response:', response);
                return { issues: [], total_count: 0 };
            },
            transformErrorResponse: (response) => {
                console.error('Lens issues API error:', response);
                return response.data?.detail || 'Unknown error';
            },
        }),
        addLensIssues: builder.mutation({
            query: (lensIssues) => ({
                url: '/lens_issues/',
                method: 'POST',
                body: lensIssues,
            }),
            invalidatesTags: ['LensIssues'],
        }),
    }),
});

export const {
    useGetLensIssuesQuery,
    useAddLensIssuesMutation,
} = lensIssuesApi;