import { cookiesKey, defaultSettings } from '../constants/config';

type CookieOptions = {
  path?: string;
  expires?: Date | string;
  themeMode?: string;
  param?: boolean;
  [index: string]: unknown;
};

export const set = (name: string, value: string, options$: CookieOptions = {}) => {
  if (typeof document === 'undefined') {
    return;
  }
  const options = {
    path: '/',
    ...options$,
  };

  if (options.expires instanceof Date) {
    options.expires = options.expires.toUTCString();
  }

  let updatedCookie = `${encodeURIComponent(name)}=${encodeURIComponent(value)}`;

  Object.entries(options).forEach(([optionKey, optionValue]) => {
    updatedCookie += `; ${optionKey}`;

    if (optionValue !== true) {
      updatedCookie += `=${optionValue}`;
    }
  });

  document.cookie = updatedCookie;
};

export const getSettings = (cookieString: string) => {
  const cookies: CookieOptions = cookieString
    .split(';')
    .map((v) => v.split('='))
    .reduce((acc, v) => {
      acc[decodeURIComponent(v[0].trim())] = decodeURIComponent(v[1]?.trim());
      return acc;
    }, {} as CookieOptions);

  return {
    themeMode: cookies[cookiesKey.themeMode] ?? defaultSettings.themeMode,
  };
};
