import { apiApp } from './api';

/**
 * @typedef {object} CouchDbReturn
 * @property {string} connect
 * @property {string} db
 * @property {string} url
 */

/**
 *
 * @param {string} databaseName
 * @returns {Promise<CouchDbReturn>}
 */
export const getCouchDatabase = async (databaseName) => {
  return (await apiApp.post('/extension/db/get', {
    databaseName,
  })).data;
};

/**
 *
 * @param {string} databaseName
 * @returns {Promise<CouchDbReturn>}
 */
export const createCouchDatabase = async (databaseName) => {
  return (await apiApp.post('/extension/db/create', {
    databaseName,
  })).data;
};

/**
 *
 * @param {string} databaseName
 * @returns {Promise<CouchDbReturn>}
 */
export const fetchCouchDatabase = async (databaseName) => {
  const result = await getCouchDatabase(databaseName);

  if (result && result.connect && result.db) {
    return result;
  }

  return createCouchDatabase(databaseName);
};
