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

export interface FaqData {
  id: number;
  principal_type_xid: number;
  is_active: number;
  translations:{
    id: string,
    faqs_xid: number,
    language_master_xid: number,
    question: string,
    answer: string,
  }[]
}

interface ApiResponse {
  status: string;
  status_code: number;
  message: string;
  data: { 
    current_page: number,
    last_page: number,
    total: number,
    from: number,
    per_page: number,
    to: number,
    data: FaqData[];
  };
}


export type Post = {
  principal_type_xid: number;
  language_code: string;
  question: string;
  answer: string;
};


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

    updateFaq: builder.mutation({
      query: (updatedData) => ({
        url: "/faq-update",
        method: "POST",
        body: updatedData,
      }),
    }),

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

    deleteFaqPost: builder.mutation<{ status: string; message: string }, { id: number }>({
      query: ({ id }) => ({
        url: `/faq-delete`,
        method: "POST",
        body: { id },
      }),
    }),

  }),
});

export const {
  useGetFaqQuery,
  useCreateFaqPostMutation,
  useUpdateFaqMutation,
  useFaqToggleMutation,
  useDeleteFaqPostMutation
} = faqs;