import cookie from 'cookie';

export const MOBILE_OPT_OUT_COOKIE_NAME = 'mobile_opt_out';
export const UPSELL_OPT_OUT_COOKIE_NAME = 'upsell_opt_out';
export const UNIQUE_ID_COOKIE_NAME = 'unique_id';
export const LANGUAGE_COOKIE_NAME = 'language';

export type OptOutCookieName =
  | typeof MOBILE_OPT_OUT_COOKIE_NAME
  | typeof UPSELL_OPT_OUT_COOKIE_NAME;

export type TrackingCookie = Record<typeof UNIQUE_ID_COOKIE_NAME, string>;
export type OptOutCookie = Record<OptOutCookieName, boolean>;
export type UsabilityCookie = Record<typeof LANGUAGE_COOKIE_NAME, string>;

export type MobileWebCookie = Partial<
  UsabilityCookie & OptOutCookie & TrackingCookie
>;

// Conveniently wrap `cookie.parse` to have a nicer type.
export function parseCookie(cookieString: string): MobileWebCookie {
  return cookie.parse(cookieString);
}

export function setCookie(
  name: keyof MobileWebCookie,
  value: string,
  maxAge: number,
  document: Record<'cookie', string>,
): void {
  document.cookie = cookie.serialize(name, value, {
    domain: 'twitch.tv',
    maxAge: maxAge,
    path: '/',
  });
}
