import {
  addQueryParams,
  errorHandler,
  fetchRespHandler,
  getAuthHeaderOptions,
} from "../utils/http";

const API_ENDPOINT = process.env.REACT_APP_OTA_SERVICE_URL;

const DTCTimelineAPI = {
  getDTCData: async (vin, ecu, troubleCode, startDate, endDate, search, token) => {
    const queryParams = {
      ecu,
      trouble_code: troubleCode,
      start_time: startDate,
      end_time: endDate,
      decode: true,
      ...search,
    };
    const url = addQueryParams(`${API_ENDPOINT}/dtcs/${vin}`, queryParams);
    return fetch(url, {
      method: "GET",
      headers: Object.assign(
        { "Content-Type": "application/json" },
        getAuthHeaderOptions(token)
      ),
    })
      .then(fetchRespHandler)
      .catch(errorHandler);
  },

  exportDTCData: async (vin, ecu, troubleCode, startDate, endDate, search, token) => {
    const queryParams = {
      ecu,
      trouble_code: troubleCode,
      start_time: startDate,
      end_time: endDate,
      decode: true,
      ...search,
    };
    const url = addQueryParams(`${API_ENDPOINT}/dtc_snapshot_export/${vin}`, queryParams);
    return fetch(url, {
      method: "GET",
      headers: Object.assign(
        { "Content-Type": "application/json" },
        getAuthHeaderOptions(token)
      ),
      responseType: "blob"
    })
      .catch(errorHandler);
  },
};

export default DTCTimelineAPI;