import { apiSlice } from "./index";
import URLS from "./constants";
import { generateQueryString } from "@/utils/queryStringUtil";

export const projectTimelineApi = apiSlice.injectEndpoints({
  endpoints: (builder) => ({
    getTimelines: builder.query<
      GetTimelineListResponse,
      { projectId: string } & TimelineQueryParams
    >({
      query: ({ projectId, ...params }) => ({
        url: `${URLS.PROJECT}/${projectId}/timelines?${generateQueryString(
          params as Record<string, unknown>
        )}`,
        method: "GET",
      }),
      providesTags: ["ProjectTimeline"],
    }),

    getTimelineById: builder.query<
      GetTimelineByIdResponse,
      { projectId: string; timelineId: string }
    >({
      query: ({ projectId, timelineId }) => ({
        url: `${URLS.PROJECT}/${projectId}/timelines/${timelineId}`,
        method: "GET",
      }),
      providesTags: (result, error, { timelineId }) => [
        { type: "ProjectTimeline", id: timelineId },
      ],
    }),

    createTimeline: builder.mutation<
      Timeline,
      { projectId: string; body: CreateTimelineRequest }
    >({
      query: ({ projectId, body }) => ({
        url: `${URLS.PROJECT}/${projectId}/timelines`,
        method: "POST",
        body,
      }),
      invalidatesTags: ["ProjectTimeline"],
    }),

    updateTimeline: builder.mutation<
      Timeline,
      { projectId: string; timelineId: string; body: UpdateTimelineRequest }
    >({
      query: ({ projectId, timelineId, body }) => ({
        url: `${URLS.PROJECT}/${projectId}/timelines/${timelineId}`,
        method: "PATCH",
        body,
      }),
      invalidatesTags: (result, error, { timelineId }) => [
        { type: "ProjectTimeline", id: timelineId },
        "ProjectTimeline",
      ],
    }),

    deleteTimeline: builder.mutation<
      { success: boolean },
      { projectId: string; timelineId: string }
    >({
      query: ({ projectId, timelineId }) => ({
        url: `${URLS.PROJECT}/${projectId}/timelines/${timelineId}`,
        method: "DELETE",
      }),
      invalidatesTags: ["ProjectTimeline"],
    }),
  }),
});

export const {
  useGetTimelinesQuery,
  useGetTimelineByIdQuery,
  useCreateTimelineMutation,
  useUpdateTimelineMutation,
  useDeleteTimelineMutation,
} = projectTimelineApi;
