const ACCESS_TOKEN_KEY = 'ms_access_token';
const REFRESH_TOKEN_KEY = 'ms_refresh_token';

const ACCESS_TOKEN_MAX_AGE = 60 * 60;
const REFRESH_TOKEN_MAX_AGE = 60 * 60 * 24 * 30;

const isProd = process.env.NODE_ENV === 'production';

const escapeRegExp = (value: string) =>
  value.replace(/[.$?*|{}()[\]\\/+^]/g, '\\$&');

const readCookie = (name: string): string | null => {
  if (typeof document === 'undefined') return null;
  const match = document.cookie.match(
    new RegExp('(?:^|; )' + escapeRegExp(name) + '=([^;]*)')
  );
  return match ? decodeURIComponent(match[1]) : null;
};

const writeCookie = (name: string, value: string, maxAgeSeconds?: number) => {
  if (typeof document === 'undefined') return;
  const parts = [
    `${name}=${encodeURIComponent(value)}`,
    'Path=/',
    'SameSite=Lax',
  ];
  if (maxAgeSeconds !== undefined) parts.push(`Max-Age=${maxAgeSeconds}`);
  if (isProd) parts.push('Secure');
  document.cookie = parts.join('; ');
};

const removeCookie = (name: string) => {
  if (typeof document === 'undefined') return;
  document.cookie = `${name}=; Max-Age=0; Path=/; SameSite=Lax`;
};

export const getAccessToken = () => readCookie(ACCESS_TOKEN_KEY);
export const getRefreshToken = () => readCookie(REFRESH_TOKEN_KEY);

export const setAuthTokens = (
  token: string,
  refreshToken: string,
  rememberMe = true,
) => {
  writeCookie(ACCESS_TOKEN_KEY, token, rememberMe ? ACCESS_TOKEN_MAX_AGE : undefined);
  writeCookie(REFRESH_TOKEN_KEY, refreshToken, rememberMe ? REFRESH_TOKEN_MAX_AGE : undefined);
};

export const clearAuthTokens = () => {
  removeCookie(ACCESS_TOKEN_KEY);
  removeCookie(REFRESH_TOKEN_KEY);
};
