const COOKIE_NAME = "refresh_token";

function cookieDomain(host) {
  if (!host) return undefined;
  const hostname = host.split(":")[0];
  if (hostname.includes("localhost") || /^\d+\.\d+\.\d+\.\d+$/.test(hostname)) {
    return undefined;
  }
  return "." + hostname.split(".").slice(-2).join(".");
}

const isSecure = process.env.NODE_ENV === "production";

export function setRefreshCookie(response, refreshToken, host, maxAge = 60 * 60 * 24 * 30) {
  response.cookies.set(COOKIE_NAME, refreshToken, {
    httpOnly: true,
    secure: isSecure,
    sameSite: "lax",
    path: "/",
    maxAge,
    domain: cookieDomain(host),
  });
}

export function clearRefreshCookie(response, host) {
  response.cookies.set(COOKIE_NAME, "", {
    httpOnly: true,
    secure: isSecure,
    sameSite: "lax",
    path: "/",
    maxAge: 0,
    domain: cookieDomain(host),
  });
}

export { COOKIE_NAME };
