export function parseAccessToken(
  token: string,
): MasterModel.TokenParsedTransformed | null {
  if (!token) return null;

  try {
    const base64Url = token.split('.')[1];
    const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
    const jsonPayload = decodeURIComponent(
      atob(base64)
        .split('')
        .map((c) => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2))
        .join(''),
    );
    const accessToken: MasterModel.TokenParsed = JSON.parse(jsonPayload);
    return {
      expriresAt: accessToken.exp,
      issuedAt: accessToken.iat,
      issuer: accessToken.iss,
      subject: accessToken.sub,
      issuerId: accessToken.issuer_id,
      type: accessToken.type,
      purpose: 'access',
    };
  } catch (error) {
    return null;
  }
}
export function parseRefreshToken(
  refreshToken: string,
): MasterModel.RefreshTokenParsedTransformed | null {
  if (!refreshToken) return null;

  const base64Url = refreshToken.split('.')[1];
  const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
  const jsonPayload = decodeURIComponent(
    atob(base64)
      .split('')
      .map((c) => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2))
      .join(''),
  );
  const refreshTokenParsed: MasterModel.RefreshTokenParsed =
    JSON.parse(jsonPayload);
  return {
    expriresAt: refreshTokenParsed.exp,
    issuedAt: refreshTokenParsed.iat,
    issuer: refreshTokenParsed.iss,
    subject: refreshTokenParsed.sub,
    issuerId: refreshTokenParsed.issuer_id,
    type: refreshTokenParsed.type,
    purpose: 'refresh',
    jwtID: refreshTokenParsed.jti,
  };
}

export function checkRefreshTokenExpired(token: string): boolean {
  const parsed = parseRefreshToken(token);
  if (!parsed) return true;
  const { expriresAt } = parsed;
  const now = Math.floor(Date.now() / 1000);
  const fiveMinutes = 60 * 5; // 5 minutes
  if (expriresAt - now < fiveMinutes) {
    return true;
  }
  return false;
}
