export const SESSION_TTL = 60 * 60 * 24 * 30;

function isIP(host) {
  return /^\d{1,3}(\.\d{1,3}){3}$/.test(host);
}

function isLocalhost(host) {
  if (!host) return false;
  const hostname = host.split(':')[0].toLowerCase();
  return hostname === 'localhost' || isIP(hostname);
}

function getDomain(host) {
  const hostname = host.split(':')[0].toLowerCase();
  const parts = hostname.split('.');

  return parts.length >= 2 ? `${parts[parts.length - 2]}.${parts[parts.length - 1]}` : undefined;
}

export const getSessionOptionsWithRequest = (req) => {
  const host = req?.headers?.host;
  const localhost = isLocalhost(host);

  const cookieOptions = {
    httpOnly: true,
    secure: process.env.NODE_ENV === 'production' && !localhost,
    sameSite: process.env.NODE_ENV === 'production' && !localhost ? 'none' : 'lax',
    maxAge: SESSION_TTL - 60,
    path: '/',
    ...(process.env.NODE_ENV === 'production' && host && !localhost
      ? (() => {
          const domain = getDomain(host);
          return domain ? { domain } : {};
        })()
      : {}),
  };

  let ttl = SESSION_TTL;

  const token = req?.body?.token;
  if (token) {
    try {
      const payload = JSON.parse(Buffer.from(token.split('.')[1], 'base64').toString());
      const exp = Number(payload?.exp);
      if (Number.isFinite(exp)) {
        ttl = Math.max(0, exp - Math.floor(Date.now() / 1000));
      }
    } catch {
      /* empty */
    }
  }

  return {
    password: process.env.SESSION_PASSWORD || '9ee5tf6fkAX2JRtZPhFyDs9cm0sG6d6A',
    cookieName:
      process.env.NODE_ENV === 'production' ? 'session' : `session-local-${process.env.APP_CONFIG_ENV || 'dev'}`,
    ttl,
    cookieOptions,
  };
};

export default {};
