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

const API_ENDPOINT = process.env.REACT_APP_OTA_SERVICE_URL;

const manifestsAPI = {
  archiveManifest: async (data, token) =>
    fetch(`${API_ENDPOINT}/vehicles/archive`, {
      method: "PUT",
      headers: Object.assign(
        { "Content-Type": "application/json" },
        getAuthHeaderOptions(token)
      ),
      body: JSON.stringify(data)
    })
      .then(fetchRespHandler)
      .catch(errorHandler),

  deleteManifest: async (manifest_id, token) =>
    fetch(`${API_ENDPOINT}/manifest?id=${manifest_id}`, {
      method: "DELETE",
      headers: Object.assign(
        { "Content-Type": "application/json" },
        getAuthHeaderOptions(token)
      ),
    })
      .then(fetchRespHandler)
      .catch(errorHandler),

  getManifest: async (id, token) => {
    const u = addQueryParams(`${API_ENDPOINT}/manifest`, { id });
    return fetch(u, {
      method: "GET",
      headers: Object.assign(
        { "Content-Type": "application/json" },
        getAuthHeaderOptions(token)
      ),
    })
      .then(fetchRespHandler)
      .catch(errorHandler);
  },

  updateManifest: async (manifest_id, data, token) => {
    return fetch(`${API_ENDPOINT}/manifest?id=${manifest_id}`, {
      method: "PUT",
      headers: Object.assign(
        { "Content-Type": "application/json" },
        getAuthHeaderOptions(token)
      ),
      body: JSON.stringify(data),
    })
      .then(fetchRespHandler)
      .catch(errorHandler);
  },

  getManifests: async (search, token) => {
    const u = addQueryParams(`${API_ENDPOINT}/manifests`, search);
    return fetch(u, {
      method: "GET",
      headers: Object.assign(
        { "Content-Type": "application/json" },
        getAuthHeaderOptions(token)
      ),
    })
      .then(fetchRespHandler)
      .catch(errorHandler);
  },

  createManifest: async (data, token) =>
    fetch(`${API_ENDPOINT}/manifest`, {
      method: "POST",
      headers: Object.assign(
        { "Content-Type": "application/json" },
        getAuthHeaderOptions(token)
      ),
      body: JSON.stringify(data),
    })
      .then(fetchRespHandler)
      .catch(errorHandler),

  createManifestECU: async (data, token) =>
    fetch(`${API_ENDPOINT}/manifestecu`, {
      method: "POST",
      headers: Object.assign(
        { "Content-Type": "application/json" },
        getAuthHeaderOptions(token)
      ),
      body: JSON.stringify(data),
    })
      .then(fetchRespHandler)
      .catch(errorHandler),

  migrateManifest: async (manifest_id, token) =>
    fetch(`${API_ENDPOINT}/manifestmigrate/${manifest_id}`, {
      method: "POST",
      headers: Object.assign(
        { "Content-Type": "application/json" },
        getAuthHeaderOptions(token)
      ),
    })
      .then(fetchRespHandler)
      .catch(errorHandler),
};

export default manifestsAPI;
