import { baseApi } from "@/store/api/baseApi";
import { Comment } from "@/store/models/Comment.model";

export const commentsApi = baseApi.injectEndpoints({
  overrideExisting: false,
  endpoints: (builder) => ({
    getTodoComments: builder.query<Comment[], string>({
      query: (todoId) => ({ url: `/todos/${todoId}/comments` }),
      providesTags: (_result, _error, todoId) => [
        { type: "Todos", id: `comments-${todoId}` },
      ],
    }),

    addComment: builder.mutation<Comment, { todoId: string; content: string }>({
      query: ({ todoId, content }) => ({
        url: `/todos/${todoId}/comments`,
        method: "POST",
        body: { content },
      }),
      invalidatesTags: (_result, _error, { todoId }) => [
        { type: "Todos", id: `comments-${todoId}` },
      ],
    }),

    updateComment: builder.mutation<
      Comment,
      { todoId: string; commentId: string; content: string }
    >({
      query: ({ todoId, commentId, content }) => ({
        url: `/todos/${todoId}/comments/${commentId}`,
        method: "PUT",
        body: { content },
      }),
      invalidatesTags: (_result, _error, { todoId }) => [
        { type: "Todos", id: `comments-${todoId}` },
      ],
    }),

    deleteComment: builder.mutation<
      { message: string },
      { todoId: string; commentId: string }
    >({
      query: ({ todoId, commentId }) => ({
        url: `/todos/${todoId}/comments/${commentId}`,
        method: "DELETE",
      }),
      invalidatesTags: (_result, _error, { todoId }) => [
        { type: "Todos", id: `comments-${todoId}` },
      ],
    }),
  }),
});

export const {
  useGetTodoCommentsQuery,
  useAddCommentMutation,
  useUpdateCommentMutation,
  useDeleteCommentMutation,
} = commentsApi;
