import axios from "axios";
import Failure from "core/failure";
import { SearchResults } from "searchResults/domain/searchResultsEntity";
import { SearchResultsDTO } from "./dto/searchResultsDTO";
import { create } from "../domain/searchResultsModel";
import { integratorApiClient } from "core/httpClient";

const searchEndpoint = "/papers/search";

async function search(request: string): Promise<SearchResults> {
  try {
    const response = await integratorApiClient.get<SearchResultsDTO>(
      searchEndpoint + `?query=` + request 
      // "https://run.mocky.io/v3/ea705665-2479-4039-8b81-412e011fc145"
    );
    const dto = response.data;
    return create({
      data: dto.data.map((e) => {
        return {
          authors: e.authors,
          content: e.content,
          id: e.id,
          summary: e.summary,
          tags: e.tags,
          title: e.title,
          topic: e.topic,
        }
      }), meta: dto.meta
    });
  } catch (reason) {
    if (axios.isAxiosError(reason)) {
      throw Failure.fromReason(reason, "failures.services.load");
    }
    throw reason;
  }
}
export { search };
