const fs = require('fs');

const axios = require('../../axios');

const getContents = require('./get-contents');

/**
 * @param {string} host
 * @param {string} productId
 * @param {string | undefined} subProductId
 * @param {string} contentsLocation
 * @param {string} token
 * @returns {Promise<*>}
 */
async function updateContents(host, productId, subProductId, contentsLocation, token) {
  let data;

  try {
    data = JSON.parse(fs.readFileSync(contentsLocation, 'utf-8'));
  } catch (e) {
    // ignore
    return Promise.resolve();
  }

  const subProductChunk = subProductId ? `/subproducts/${subProductId}` : '';

  const existingContents = await getContents(host, productId, subProductId, token);

  if (!existingContents) {
    return axios.post(
      `https://api.${host}/v2/products/${productId}${subProductChunk}/contents`,
      {
        data,
      },
      {
        headers: {
          Authorization: `Bearer ${token}`,
          'Content-Type': 'application/json',
        },
      },
    );
  }

  return axios.patch(
    `https://api.${host}/v2/products/${productId}${subProductChunk}/contents`,
    {
      data,
    },
    {
      headers: {
        Authorization: `Bearer ${token}`,
        'Content-Type': 'application/json',
      },
    },
  );
}

module.exports = updateContents;
