import {
  browserCookieGetAll, browserCookieGet, browserCookieSet, browserCookieRemove,
} from './api';
import { loggerContent } from '@/plugins/logger';

/**
 *
 * @param {string} url
 * @returns {Promise<BrowserCookieStore[]>}
 */
export const getAllCookies = async (url) => {
  if (typeof browserCookieGetAll !== 'function') {
    return [];
  }

  try {
    const listCookie = (await browserCookieGetAll({
      url,
    })) || [];

    return listCookie.map((item) => ({
      ...item,
      key: item.name,
    }));
  } catch (error) {
    loggerContent.error({
      msg: 'GET_ALL_COOKIES_ERROR',
      url,
      error,
    });
    return [];
  }
};

export const getKeyCookie = async (name, url) => {
  if (typeof browserCookieGet !== 'function') {
    return '';
  }

  try {
    const cookie = await browserCookieGet({
      url,
      name,
    });

    if (!(cookie && cookie.value)) {
      return '';
    }

    return cookie.value;
  } catch (error) {
    loggerContent.error({
      msg: 'GET_KEY_COOKIES_ERROR',
      name,
      url,
      error,
    });
    return '';
  }
};

/**
 *
 * @param {string} name
 * @param {string} value
 * @param {string} url
 * @param {string} domain
 * @param {*} timeExpried
 * @returns
 */
export const setKeyCookie = async (name, value, url, domain, timeExpried = 0) => {
  if (typeof browserCookieSet !== 'function') {
    return false;
  }

  const payloadSet = {
    name,
    value,
  };

  if (timeExpried) {
    const timeExpriedDefault = Math.ceil(new Date().getTime() / 1000) + 31536000;
    payloadSet.expirationDate = Number(timeExpried) || timeExpriedDefault;
  }

  if (url) {
    payloadSet.url = url;
  }

  if (domain) {
    payloadSet.domain = domain;
  }

  return browserCookieSet(payloadSet);
};

export const removeKeyCookie = async (name, url) => {
  if (typeof browserCookieRemove !== 'function') {
    return false;
  }

  return browserCookieRemove({
    url,
    name,
  });
};

export const getKeyCookieNative = (name) => {
  const value = `; ${document.cookie}`;
  const parts = value.split(`; ${name}=`);

  if (parts.length === 2) {
    return parts.pop().split(';').shift();
  }

  return '';
};

export const getAllCookieNative = () => {
  const cookies = document.cookie;

  const arrayCookies = cookies.split(';');

  return arrayCookies.map((item) => {
    const [name, value] = item.split('=');
    return {
      key: name,
      name,
      value,
    };
  });
};
