import { integratorApiClient } from "auth/data/authService";
import axios from "axios";
import { DTOModel } from "core/dto_model";
import Failure from "core/failure";
import { Service } from "services/domain/serviceEntity";
import { create } from "services/domain/serviceModel";
import { ServiceDTO } from "./dto/serviceDTO";

async function loadServices(): Promise<Service[]> {
  try {
    const response = await integratorApiClient
    .get<DTOModel<ServiceDTO[]>>("/service");
    const content = response.data.data;
    return content.map((dto) => {
      return create({
        id: dto._id,
        name: dto.title,
        shortName: dto.short_name,
        href: dto.address,
        category: dto.category,
        variant: dto.color,
        subscribed: false,
      })
    });
  } catch (reason) {
    if(axios.isAxiosError(reason)) {
      throw Failure.fromReason(reason, "failures.services.load");
    }
    throw reason;
  }
}


export { loadServices };
