import { apiInstance, getMediaUrl } from "../apiConfig";

const ContentAPI = {
  async getStartStation(startStopId, lang = "ru") {
    if (!startStopId) {
      console.warn("startStopId не указан.");
      return null;
    }

    try {
      const response = await apiInstance.get(
        `/station/${startStopId}?lang=${lang}`
      );
      return response.data;
    } catch (error) {
      console.error("Ошибка при запросе:", error.message);
      throw error;
    }
  },

  async getEndStation(endStopId, lang = "ru") {
    if (!endStopId) {
      console.warn("endStopId не указан.");
      return null;
    }

    try {
      const response = await apiInstance.get(
        `/station/${endStopId}?lang=${lang}`
      );
      return response.data;
    } catch (error) {
      console.error("Ошибка при запросе:", error.message);
      throw error;
    }
  },

  async getListOfStations(id, lang = "ru") {
    try {
      const responce = await apiInstance.get(
        `/route/${id}/station?lang=${lang}`
      );

      return responce.data;
    } catch (error) {
      console.error("Ошибка при запросе:", error.message);
      throw error;
    }
  },

  async getRoutePath(id, lang = "ru") {
    try {
      const responce = await apiInstance.get(`/route/${id}?lang=${lang}`);
      return responce.data;
    } catch (error) {
      console.error("Ошибка при запросе:", error.message);
      throw error;
    }
  },

  async getRouteSights(id, lang = "ru") {
    try {
      const responce = await apiInstance.get(
        `/route/${id}/sight?lang=${lang}`
      );
      return responce.data;
    } catch (error) {
      console.error("Ошибка при запросе:", error.message);
      throw error;
    }
  },

  async getSightData(id, lang = "ru") {
    try {
      const responce = await apiInstance.get(`/sight/${id}?lang=${lang}`);
      return responce.data;
    } catch (error) {
      console.error("Ошибка при запросе:", error.message);
      throw error;
    }
  },

  async getSightArticle(id, lang = "ru") {
    try {
      const responce = await apiInstance.get(
        `/sight/${id}/article?lang=${lang}`
      );
      return responce.data;
    } catch (error) {
      console.error("Ошибка при запросе:", error.message);
      throw error;
    }
  },

  async getMedia(id, lang = "ru", signal) {
    try {
      const responce = await apiInstance.get(
        `/article/${id}/media?lang=${lang}`,
        { signal }
      );
      return {
        path: getMediaUrl(responce.data[0].id),
        type: responce.data[0].media_type,
      };
    } catch (error) {
      console.error("Ошибка в получении медиа:", error.message);
      throw error;
    }
  },

  async getMediaPreview(id, lang = "ru", signal) {
    try {
      const responce = await apiInstance.get(
        `/media/${id}?lang=${lang}`,
        { signal }
      );
      return {
        path: getMediaUrl(id),
        type: responce.data.media_type,
      };
    } catch (error) {
      console.error("Ошибка в получении медиа-превью:", error.message);
      throw error;
    }
  },

  async getCarrierAndCrestByRoute(id, lang = "ru") {
    try {
      const responce = await apiInstance.get(`/route/${id}?lang=${lang}`);
      const carrier = await apiInstance.get(
        `/carrier/${responce.data.carrier_id}?lang=${lang}`
      );
      const creast = await apiInstance.get(
        `/city/${carrier.data.city_id}?lang=${lang}`
      );
      return {
        carrierPath: getMediaUrl(carrier.data.logo),
        creastPath: getMediaUrl(creast.data.arms),
      };
    } catch (error) {
      console.error("Ошибка в получении герба:", error.message);
      throw error;
    }
  },

  async getLeftArticle(id, lang = "ru") {
    try {
      const responce = await apiInstance.get(`/sight/${id}?lang=${lang}`);
      const leftArticle = await apiInstance.get(
        `/article/${responce.data.left_article}?lang=${lang}`
      );
      const leftArticleMedia = await apiInstance.get(
        `/article/${leftArticle.data.id}/media?lang=${lang}`
      );
      if (leftArticleMedia.data.length == 0) {
        return {
          mediaPath: null,
          mediaType: null,
          title: leftArticle.data.heading,
          text: leftArticle.data.body,
          address: responce.data.address,
        };
      }
      return {
        mediaPath: getMediaUrl(leftArticleMedia.data[0].id),
        mediaType: leftArticleMedia.data[0].media_type,
        title: leftArticle.data.heading,
        text: leftArticle.data.body,
        address: responce.data.address,
      };
    } catch (error) {
      console.error(
        "Ошибка в получении информации для левого виджета:",
        error.message
      );
      throw error;
    }
  },

  async getListOfTransfer(routeId, stationId, lang = "ru") {
    try {
      const response = await apiInstance.get(
        `/route/${routeId}/station?lang=${lang}`
      );
      const stationData = response.data.find((s) => s.id == stationId);
      if (!stationData || !stationData.transfers) {
        return "no data";
      }

      const result = {
        tram: [],
        trolleybus: [],
        bus: [],
        train: [],
        metro_red: [],
        metro_green: [],
        metro_blue: [],
        metro_purple: [],
        metro_orange: [],
      };
      for (const type in stationData.transfers) {
        if (
          Object.hasOwnProperty.call(stationData.transfers, type) &&
          result[type] !== undefined
        ) {
          result[type] = stationData.transfers[type];
        }
      }
      return result;
    } catch (error) {
      console.error(
        "Ошибка в получении информации о пересадках:",
        error.message
      );
      throw error;
    }
  },

  getMediaPath(path) {
    return getMediaUrl(path);
  },
};

export default ContentAPI;
