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

const API_ENDPOINT = process.env.REACT_APP_OTA_SERVICE_URL;

const canFiltersAPI = {
  addFilter: async (vin, filter, token) =>
    fetch(`${API_ENDPOINT}/vehicle/${vin}/filter`, {
      method: "POST",
      headers: Object.assign(
        { "Content-Type": "application/json" },
        getAuthHeaderOptions(token)
      ),
      body: JSON.stringify(filter),
    })
      .then(fetchRespHandler)
      .catch(errorHandler),

  getFilters: async (vin, search, token) =>
    fetch(addQueryParams(`${API_ENDPOINT}/vehicle/${vin}/filters`, search), {
      method: "GET",
      headers: Object.assign(
        { "Content-Type": "application/json" },
        getAuthHeaderOptions(token)
      ),
    })
      .then(fetchRespHandler)
      .catch(errorHandler),

  updateFilter: async (vin, canID, filter, token) =>
    fetch(`${API_ENDPOINT}/vehicle/${vin}/filter/${canID}`, {
      method: "PUT",
      headers: Object.assign(
        { "Content-Type": "application/json" },
        getAuthHeaderOptions(token)
      ),
      body: JSON.stringify(filter),
    })
      .then(fetchRespHandler)
      .catch(errorHandler),

  deleteFilter: async (vin, canID, token) =>
    fetch(`${API_ENDPOINT}/vehicle/${vin}/filter/${canID}`, {
      method: "DELETE",
      headers: Object.assign(
        { "Content-Type": "application/json" },
        getAuthHeaderOptions(token)
      ),
    })
      .then(fetchRespHandler)
      .catch(errorHandler),
};

export default canFiltersAPI;
