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

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

interface PaginationData {
  current_page: number;
  data: Template[];
  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 Template {
  id: number;
  is_active: boolean;
  principle_type_xid: number;
  post_template_translate: PostTemplateTranslate[];
  post_template_image: PostTemplateImage[];
}

export interface PostTemplateTranslate {
  id: number;
  title: string;
  sub_title: string;
  post_template_xid: number;
}

interface PostTemplateImage {
  id: number;
  post_template_xid: number;
  image_name: string;
}

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

export interface Post {
  id: number,
  principle_type_xid: number,
  title: string,
  sub_title: string,
  image_name: string[]
}

export const templateMaster = createApi({
  reducerPath: "templateMaster",
  baseQuery: baseQueryWithReauth, // Use enhanced baseQuery with error handling
  endpoints: (builder) => ({
    createTemplatePost: builder.mutation<Post, FormData>({
      query: (data) => ({
        url: "/template-store",
        method: "POST",
        body: data,
        headers: {
          Authorization: `Bearer ${localStorage.getItem("token")}`,
        },
      }),
    }),
    // 🔹 GET: Fetch all posts
    getTemplateMaster: builder.query<TemplateResponse, number>({
      query: (page = 1) => `/template-master?page=${page}`,
    }),

    updateTemplateMaster: builder.mutation<Post, FormData>({
      query: (updatedData) => {
        const token = localStorage.getItem("token");
        return {
          url: "/template-update",
          method: "POST",
          body: updatedData,
          headers: {
            'access-token': `${token}`,
          },
        };
      },
    }),

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

  }),
});

export const {
  useGetTemplateMasterQuery,
  useCreateTemplatePostMutation,
  useUpdateTemplateMasterMutation,
  useTemplateMasterToggleMutation,
} = templateMaster;
