import { baseApi } from "./baseApi";
import { API_ENDPOINTS } from "./constant";
import {
  IBlogCategory,
  IBlogCommentsBlock,
  IBlogPostDetail,
  IBlogPostsResponseData,
  IPagesResponseData,
} from "./types/blog";

export const blogApi = baseApi.injectEndpoints({
  endpoints: (builder) => ({
    getBlogCategories: builder.query<IBlogCategory[], void>({
      query: () => ({
        url: `${API_ENDPOINTS.blogCategories}?sortBy=id&sortDirection=desc`,
        method: "GET",
      }),
    }),
    getBlogPosts: builder.query<
      IBlogPostsResponseData,
      {
        page: number;
        perPage?: number;
        categoryId?: number;
        searchText?: string;
      }
    >({
      query: ({ page, perPage = 21, categoryId, searchText }) => ({
        url: API_ENDPOINTS.blogPosts,
        method: "GET",
        params: {
          page,
          perPage,
          sortBy: "publishedAt",
          sortDirection: "desc",
          // premiumEvery: 3,
          ...(categoryId ? { categoryId } : {}),
          ...(searchText ? { searchText } : {}),
        },
      }),
    }),
    getPages: builder.query<IPagesResponseData, void>({
      query: () => ({
        url: API_ENDPOINTS.pageList,
        method: "GET",
        params: { page: 1, perPage: 20, sortBy: "id", sortDirection: "asc" },
      }),
    }),
    getBlogPostByCode: builder.query<IBlogPostDetail, string>({
      query: (code) => ({
        url: `${API_ENDPOINTS.blogPostByCode}/${code}`,
        method: "GET",
      }),
      providesTags: (_result, _error, code) => [{ type: "BlogPost", id: code }],
    }),
    createComment: builder.mutation<
      unknown,
      { postId: number; content: string; parentId?: number; postCode?: string }
    >({
      query: ({ postId, content, parentId }) => ({
        url: API_ENDPOINTS.comment,
        method: "POST",
        body: {
          postId,
          content,
          ...(parentId ? { parentId } : {}),
        },
      }),
      invalidatesTags: (_result, _error, { postCode }) =>
        postCode ? [{ type: "BlogPost", id: postCode }] : [],
    }),
    getComments: builder.query<
      IBlogCommentsBlock,
      {
        postId: number;
        page?: number;
        perPage?: number;
        parentId?: number;
        sortDirection?: string;
      }
    >({
      query: ({ postId, page = 1, perPage = 20, parentId, sortDirection }) => ({
        url: API_ENDPOINTS.commentList,
        method: "GET",
        params: {
          page,
          perPage,
          sortBy: "id",
          sortDirection: sortDirection || "desc",
          postId,
          ...(parentId ? { parentId } : {}),
        },
      }),
    }),
  }),
});

export const {
  useGetBlogCategoriesQuery,
  useGetBlogPostsQuery,
  useLazyGetBlogPostsQuery,
  useGetPagesQuery,
  useGetBlogPostByCodeQuery,
  useCreateCommentMutation,
  useLazyGetCommentsQuery,
} = blogApi;
