import 'server-only';

import { cookies as nextCookies } from 'next/headers';

const CookieName = {
  MEDUSA_CUSTOMER_ID: '_medusa_customer_id',
  MEDUSA_JWT: '_medusa_jwt',
  MEDUSA_CART_ID: '_medusa_cart_id',
  MEDUSA_CACHE_ID: '_medusa_cache_id',
};

export const getAuthHeaders = async (): Promise<
  { authorization: string } | {}
> => {
  try {
    const cookies = await nextCookies();
    const token = cookies.get(CookieName.MEDUSA_JWT)?.value;

    if (!token) {
      return {};
    }

    return { authorization: `Bearer ${token}` };
  } catch {
    return {};
  }
};

export const getMedusaCustomerId = async (): Promise<{
  customerId: string | null;
}> => {
  try {
    const cookies = await nextCookies();
    const customerId = cookies.get(CookieName.MEDUSA_CUSTOMER_ID)?.value;

    if (!customerId) {
      return { customerId: null };
    }

    return { customerId };
  } catch {
    return { customerId: null };
  }
};

export const getCacheTag = async (tag: string): Promise<string> => {
  try {
    const cookies = await nextCookies();
    const cacheId = cookies.get(CookieName.MEDUSA_CACHE_ID)?.value;

    if (!cacheId) {
      return '';
    }

    return `${tag}-${cacheId}`;
  } catch (error) {
    return '';
  }
};

export const getCacheOptions = async (
  tag: string,
): Promise<{ tags: string[] } | {}> => {
  if (typeof window !== 'undefined') {
    return {};
  }

  const cacheTag = await getCacheTag(tag);

  if (!cacheTag) {
    return {};
  }

  return { tags: [`${cacheTag}`] };
};

const getCookieSharedOptions = () => ({
  maxAge: 60 * 60 * 24 * 7,
  httpOnly: false,
  secure: process.env.NODE_ENV === 'production',
});
const getCookieResetOptions = () => ({
  maxAge: -1,
});

export const setAuthToken = async (token: string) => {
  const cookies = await nextCookies();
  cookies.set(CookieName.MEDUSA_JWT, token, {
    ...getCookieSharedOptions(),
  });
};

export const setMedusaCustomerId = async (customerId: string) => {
  const cookies = await nextCookies();
  cookies.set(CookieName.MEDUSA_CUSTOMER_ID, customerId, {
    ...getCookieSharedOptions(),
  });
};

export const removeAuthToken = async () => {
  const cookies = await nextCookies();
  cookies.set(CookieName.MEDUSA_JWT, '', {
    ...getCookieResetOptions(),
  });
};

export const getCartId = async () => {
  const cookies = await nextCookies();
  return cookies.get(CookieName.MEDUSA_CART_ID)?.value;
};

export const setCartId = async (cartId: string) => {
  const cookies = await nextCookies();
  cookies.set(CookieName.MEDUSA_CART_ID, cartId, {
    ...getCookieSharedOptions(),
  });
};

export const removeCartId = async () => {
  const cookies = await nextCookies();
  cookies.set(CookieName.MEDUSA_CART_ID, '', {
    ...getCookieResetOptions(),
  });
};
