import { createApi } from "@reduxjs/toolkit/query/react";
import { baseQueryWithReauth } from "./apiSlice";

interface IndustryMasterResponse {
    status: string;
    status_code: number;
    message: string;
    data: PaginationData;
}

interface PaginationData {
    current_page: number;
    data: IndustryMaster[];
    first_page_url: string;
    from: number;
    last_page: number;
    last_page_url: string;
    links: PaginationLink[];
    next_page_url: string | null;
    path: string;
    per_page: number;
    prev_page_url: string | null;
    to: number;
    total: number;
}

export interface IndustryMaster {
    id: number;
    categories_masters_xid: number,
    is_active: boolean;
    en_name: string;
    hi_name: string;
    mr_name: string,
    te_name: string,
    ta_name: string,
    bn_name: string,
    or_name: string,
}


interface PaginationLink {
    url: string | null;
    label: string;
    active: boolean;
}

export interface Post {
    en_name: string,
    categories_masters_xid: number
}

export const industryMaster = createApi({
    reducerPath: "industryMaster",
    baseQuery: baseQueryWithReauth, // Use enhanced baseQuery with error handling
    endpoints: (builder) => ({
        createIndustryMasterPost: builder.mutation<Post, Partial<Post>>({
            query: (data) => ({
                url: "/industry-master-store",
                method: "POST",
                body: data,
            }),
        }),
        // 🔹 GET: Fetch all posts
        // getIndustryMaster: builder.query<IndustryMasterResponse, number>({
        //     query: (page = 1) => `/industry-master-list?page=${page}`,
        // }),

        getIndustryMaster: builder.query<IndustryMasterResponse, { page?: number; search?: string }>({
            query: ({ page, search }) => {
                const params = new URLSearchParams();
                if (page) params.append("page", page.toString());
                if (search) params.append("search", search);

                return `/industry-master-list?${params.toString()}`;
            },
        }),

        updateIndustryMaster: builder.mutation({
            query: (updatedData) => ({
                url: "industry-master-update",
                method: "POST",
                body: updatedData,
            }),
        }),

        industryMasterToggle: builder.mutation({
            query: ({ id, is_active }) => ({
                url: `/industry-master-status`,
                method: "POST",
                body: { id, is_active },
            }),
        }),

    }),
});

export const {
    useGetIndustryMasterQuery,
    useCreateIndustryMasterPostMutation,
    useUpdateIndustryMasterMutation,
    useIndustryMasterToggleMutation,
} = industryMaster;
