import { serializeAxiosParams } from "@/utils/shared";
import api from "../axios";
import { API_ENDPOINTS } from "../endpoints";
import { ApiResponse } from "../types";
import {
  TTenderDetails,
  TTenderDocumentsResponse,
  TTenderResponse,
  TTenderTranslationResponse,
} from "../types/Tenders";

export const tendersService = {
  tendersList: async (
    params?: Record<string, any>,
  ): Promise<ApiResponse<TTenderResponse>> => {
    try {
      return (
        await api.get(API_ENDPOINTS.TENDERS.READ_ALL, {
          params,
          paramsSerializer: serializeAxiosParams,
        })
      ).data;
    } catch (error) {
      console.error("ERROR caught in Tenders Services Read all:", error);
      throw error;
    }
  },
  tenderDetails: async (
    id: string,
    params?: Record<string, any>,
  ): Promise<ApiResponse<TTenderDetails>> => {
    try {
      return (await api.get(API_ENDPOINTS.TENDERS.DETAILS(id), { params })).data;
    } catch (error) {
      console.error(
        "ERROR caught in Tender Service => tender details: ",
        error,
      );
      throw error;
    }
  },
  translateTender: async ({
    id,
    language,
  }: {
    id: string;
    language: string;
  }): Promise<ApiResponse<TTenderTranslationResponse>> => {
    try {
      return (
        await api.post(API_ENDPOINTS.TENDERS.AI_TRANSLATE(id), {
          language,
        })
      ).data;
    } catch (error) {
      console.error("ERROR caught in Tender Service => translate tender: ", error);
      throw error;
    }
  },

  getDocuments: async (id: string): Promise<ApiResponse<TTenderDocumentsResponse[]>> => {
    try {
      return (await api.get(API_ENDPOINTS.TENDERS.DOCUMENTS(id))).data;
    } catch (error) {
      console.error("ERROR caught in Tender Service => get documents: ", error);
      throw error;
    }
  },

  /** Single file — backend expects `filename` matching the list entry. */
  downloadTenderDocument: (tenderId: string, filename: string) =>
    api.get<Blob>(API_ENDPOINTS.TENDERS.DOCUMENTS_DOWNLOAD(tenderId), {
      params: { filename },
      responseType: "blob",
    }),

  /** Optional bulk archive when the API returns a zip without extra params. */
  downloadTenderDocumentsArchive: (tenderId: string) =>
    api.get<Blob>(API_ENDPOINTS.TENDERS.DOCUMENTS_DOWNLOAD(tenderId), {
      responseType: "blob",
    }),
};
