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

export interface Quotation {
  id: string;
  companyId?: { id: string };
  project: { id: string; projectName?: string };
  termsConditions: string;
  createdBy?: { id: string };
  updatedBy?: { id: string };
}

interface GetQuotationsResponse {
  code: number;
  message: string;
  success: boolean;
  data: {
    results: Quotation[];
    page: number;
    limit: number;
    totalPages: number;
    totalResults: number;
  };
}

interface CreateQuotationBody {
  project: string;
  termsConditions: string;
}

interface UpdateQuotationBody {
  termsConditions?: string;
  project?: string;
}

interface DefaultResponse {
  code: number;
  message: string;
  success: boolean;
  data: boolean;
}

type GetQuotationsParams = {
  page?: number;
  limit?: number;
  search?: string;
  sortBy?: string;
  populate?: string;
  companyId?: string;
  project?: string;
};

export const quotationApi = apiSlice.injectEndpoints({
  endpoints: (builder) => ({
    getQuotations: builder.query<GetQuotationsResponse, GetQuotationsParams>({
      query: (params) => ({
        url: `${URLS.QUOTATION_TERMS}?${generateQueryString(
          params as Record<string, unknown>
        )}`,
        method: "GET",
      }),
      providesTags: ["Quotation"],
    }),

    createQuotation: builder.mutation<DefaultResponse, CreateQuotationBody>({
      query: (body) => ({
        url: `${URLS.QUOTATION_TERMS}`,
        method: "POST",
        body,
      }),
      invalidatesTags: ["Quotation"],
    }),

    updateQuotation: builder.mutation<
      DefaultResponse,
      { id: string } & UpdateQuotationBody
    >({
      query: ({ id, ...body }) => ({
        url: `${URLS.QUOTATION_TERMS}/${id}`,
        method: "PATCH",
        body,
      }),
      invalidatesTags: ["Quotation"],
    }),

    deleteQuotation: builder.mutation<DefaultResponse, string>({
      query: (id) => ({
        url: `${URLS.QUOTATION_TERMS}/${id}`,
        method: "DELETE",
      }),
      invalidatesTags: ["Quotation"],
    }),
  }),
  overrideExisting: false,
});

export const {
  useGetQuotationsQuery,
  useCreateQuotationMutation,
  useUpdateQuotationMutation,
  useDeleteQuotationMutation,
} = quotationApi;
