import { generateQueryString } from "@/utils/queryStringUtil";
import { apiSlice } from ".";
import URLS from "./constants";
import {
  PropertyFile,
  CreatePropertyFileRequest,
  UpdatePropertyFileRequest,
  PropertyFileFilterParams,
  GetPropertyFileListResponse,
  GetPropertyFileByIdResponse,
} from "@/types/propertyFile";

export const propertyFileApi = apiSlice.injectEndpoints({
  endpoints: (builder) => ({
    getPropertyFiles: builder.query<
      GetPropertyFileListResponse,
      PropertyFileFilterParams
    >({
      query: (params) => {
        const { propertyId, ...rest } = params;
        return {
          url: `${URLS.INDIVIDUAL_PROPERTIES}/${propertyId}/files?${generateQueryString(
            rest as Record<string, unknown>,
          )}`,
          method: "GET",
        };
      },
      providesTags: ["PropertyFiles"],
    }),

    getPropertyFileById: builder.query<
      GetPropertyFileByIdResponse,
      { propertyId: string; fileId: string }
    >({
      query: ({ propertyId, fileId }) => ({
        url: `${URLS.INDIVIDUAL_PROPERTIES}/${propertyId}/files/${fileId}`,
        method: "GET",
      }),
      providesTags: ["PropertyFiles"],
    }),

    createPropertyFile: builder.mutation<
      PropertyFile,
      { propertyId: string; body: CreatePropertyFileRequest }
    >({
      query: ({ propertyId, body }) => ({
        url: `${URLS.INDIVIDUAL_PROPERTIES}/${propertyId}/files`,
        method: "POST",
        body,
      }),
      invalidatesTags: ["PropertyFiles"],
    }),

    updatePropertyFile: builder.mutation<
      PropertyFile,
      { propertyId: string; fileId: string; body: UpdatePropertyFileRequest }
    >({
      query: ({ propertyId, fileId, body }) => ({
        url: `${URLS.INDIVIDUAL_PROPERTIES}/${propertyId}/files/${fileId}`,
        method: "PATCH",
        body,
      }),
      invalidatesTags: ["PropertyFiles"],
    }),

    deletePropertyFile: builder.mutation<
      { success: boolean },
      { propertyId: string; fileId: string }
    >({
      query: ({ propertyId, fileId }) => ({
        url: `${URLS.INDIVIDUAL_PROPERTIES}/${propertyId}/files/${fileId}`,
        method: "DELETE",
      }),
      invalidatesTags: ["PropertyFiles"],
    }),
  }),
});

export const {
  useGetPropertyFilesQuery,
  useGetPropertyFileByIdQuery,
  useCreatePropertyFileMutation,
  useUpdatePropertyFileMutation,
  useDeletePropertyFileMutation,
} = propertyFileApi;

